【问题标题】:Django TemplateSyntaxError :- How access Dictionary values for iteration?Django TemplateSyntaxError :- 如何访问字典值进行迭代?
【发布时间】:2021-01-10 22:36:29
【问题描述】:

我有一个列表和字典。其中列表值是字典的键。想要在 html 页面上显示此数据,例如将有 3 个表格,第一个是每页黑白打印,第二个是“每页正面和背面黑白打印”,第三个是每页彩色打印,如 tableTitle 列表。现在表中的数据将来自complext_dict 的各个键。所以最终输出应该是这样的:-

表 1:- 每页黑白打印,表行是 2 第一个 abcd.pdf 和第二个 abc,pdf。

表2:-每页正反面黑白打印且表格行数为零

表3:-每页彩色打印,表行为一个rp.pdf

 tableTitle = ["Per page B&W print",
                "Per page front and back B&W print",
                "Per page Color print",]


    complex_dict = {'Per page B&W print': ['abcd.pdf', 'abc.pdf'],
                    'Per page front and back B&W print': [], 
                     'Per page Color print': ['Rp.pdf']}

这是 HTML 模板

{% for title in tableTitle %}
            <div class="card">
                <div class="card-body">
                    <p>{{title}}</p>
                    <table class="table table-striped table-responsive">
                        <thead>
                            <tr>
                                <th scope="col">#</th>
                                      <th scope="col">Documet Name</th>
                                      <th scope="col">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for file in complexDict.title%}
                                <tr>
                                    <td>{{forloop.counter}}</td>
                                    <td>{{file}}</td>
                                    <td>Action</td>
                                </tr>
                                {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>

** app/views.py **

def userDashboard(request):
   tableTitle = ["Per page B&W print",
                    "Per page front and back B&W print",
                    "Per page Color print",]

  complex_dict = {'Per page B&W print': ['abcd.pdf', 'abc.pdf'],
                  'Per page front and back B&W print': [], 
                  'Per page Color print': ['Rp.pdf']}

   return render(request, "action/userDashboard.html" , {"complex_Dict":complex_Dict, "tableTitle":tableTitle})

【问题讨论】:

    标签: python django bootstrap-4 django-views django-templates


    【解决方案1】:

    要在模板中迭代一个字典,你可以使用这样的东西

    {% for key, value in dict.items %}
      <td>{{key}} - {{value}}</td>
    {% endfor %}
    

    【讨论】:

    • 我想遍历每个键的值。如果您在代码中看到每个值都是列表。并且为了维护字典的顺序访问,我有键 tableTitle 的列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多