0
0

More than 1 year has passed since last update.

Djangoのテンプレートでリストをforを使用して1件ずつ表示するとき、N件ごとにタグを入れて分割表示したい

Last updated at Posted at 2023-08-08

結論

forloop.counter0forloop.counterdivisiblebyを組み合わせて実現しました。

やりたいこと

djangoのviewクラスがリストをテンプレートに渡します。
テンプレートでforを使用して1件ずつ表示するときに、N件ごとにタグを入れて分割表示したいです。
例えば、下記のように6件のリストに対して、3件ずつに分割してテーブルとして表示するというイメージです。

views.py
# ...

class IndexView(TemplateView):
    # ...
    def get_context_data(self, **kwargs):
        # 表示したいリスト
        kwargs["members"] = [
              { "name": "taro", "age": 25 },
              { "name": "jiro", "age": 26 },
              { "name": "hanako", "age": 29 },
              { "name": "emi", "age": 24 },
              { "name": "rin", "age": 22 },
              { "name": "koichi", "age": 30 },
        ]

        return super().get_context_data(**kwargs)

# ...
理想.html
<!-- table 1つにつき3件 -->
<table class="table">
    <thead>
        <tr>
            <th>name</th>
            <th>age</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>taro</td>
            <td>25</td>
        </tr>
        <tr>
            <td>jiro</td>
            <td>26</td>
        </tr>
        <tr>
            <td>hanako</td>
            <td>29</td>
        </tr>
    </tbody>
</table>
<!-- table 1つにつき3件 -->
<table class="table">
    <thead>
        <tr>
            <th>name</th>
            <th>age</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>emi</td>
            <td>24</td>
        </tr>
        <tr>
            <td>rin</td>
            <td>22</td>
        </tr>
        <tr>
            <td>koichi</td>
            <td>30</td>
        </tr>
    </tbody>
</table>

表示

image.png

どうしたか

forloop.counter0forloop.counterdivisiblebyフィルタを組み合わせて実現しました。

説明
forloop.counter0 forの中で使用する。0から数え始めて、現在何回目のループかが格納された変数
forloop.counter forの中で使用する。1から数え始めて、現在何回目のループかが格納された変数
divisibleby 値が引数の値で割り切れる場合にTrueを返すフィルタ

サンプルコード

(前述の「IndexView」の場合)

.html
{% for member in members %}
    {# 冒頭はforloop.counter0 #}
    {% if forloop.counter0|divisibleby:3 %}
    <!-- table 1つにつき3件 -->
    <table class="table">
        <thead>
            <tr>
                <th>name</th>
                <th>age</th>
            </tr>
        </thead>
        <tbody>
    {% endif %}
            <tr>
                <td>{{member.name}}</td>
                <td>{{member.age}}</td>
            </tr>
    {# 末尾はforloop.counter #}
    {# リスト全体の最後にもタグを入れる必要がある #}
    {% if forloop.counter|divisibleby:3 or forloop.last %}
        </tbody>
    </table>
    {% endif %}
{% endfor %}

これで、やりたかったことが実現できました。

以上です。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0