首页 > 解决方案 > 如何在 django 模板中迭代多个列表

问题描述

我正在尝试在模板上迭代我的嵌套字典,但它不迭代卡片,但它返回这样的列表(第一个示例图像)而不是迭代卡片。

在此处输入图像描述 但想要迭代三个列表,如第二张图片(第二张示例图片) 在此处输入图像描述 也就是说,如果每张卡片都有相关的帖子,并且每个帖子都关联(列表)内容,

所以这是我的嵌套字典

cards = [
{'card_title': card_postings,
  'posts': [
      {'post_title': arrays,
        'contents': post_content,}
  ],
},
] 

这也是模板

      {% for card in cards %}
            <div class="card">
                <div class="card-body">
                    <h4 class="text-center">{{ card.card_title }}</h4>
                    <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
                      {% for post in cards.posts %} 
                        <div class="col">
                        <div class="card">
                            <div class="card-header text-center text-primary">
                              <h5>{{ post.post_title }}</h5>
                            </div>
                            <ul class="list-group list-group-flush">
                              <li class="list-group-item border-0">
                                {% for content in post.contents %}
                                <i>{{ content }} <br> </i> 
                                {% endfor %}
                              </li>
                            </ul>
                          </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
      {% endfor %}

顺便说一句,嵌套字典中的所有这些变量(card_postings、arrays、post_content)都是列表

标签: pythonpython-3.xdjangodjango-templates

解决方案


推荐阅读