【问题标题】:Rendering dictionary having values in list format in django template在 django 模板中呈现具有列表格式值的字典
【发布时间】:2013-09-05 19:00:23
【问题描述】:

我有像这样的字典格式:

uri_dict :{
"152.2.3.4" : ["/v1/draft" , 2],
"172.31.13.12" : ["/v1/url" , 34]
}

我想在 django 模板中以表格格式呈现这个:

{% for keys, value in url_dict.items %}
                      <tr border = 1px black> 
                        <th>{{ keys }}</th>
                        <td> {{ value[0] }} </td>      <!--requires value[0]  but not working -->
                        <td>{{ value[1]}} </td>   <!--not working -->
                        </tr>
                        {% endfor %} 

请提供任何解决方案---如何迭代模板中的列表值? 如何迭代列表值

【问题讨论】:

  • 尝试value.0value.1 等等(或者只是对值进行for 循环)。

标签: django django-forms django-templates


【解决方案1】:

有几个选项:

<td>{{ value.0 }}</td>
<td>{{ value.1 }}</td>

{% for item in value %}
    <td>{{ item }}</td>
{% endfor}

这两个都包含在我的评论中(以及之后的其他答案)。对于长度为 2 的列表,您还可以:

<td>{{ value|first }}</td>
<td>{{ value|last }}</td>

【讨论】:

    【解决方案2】:

    如果字典的每个值总是只有两个项目,即列表,那么

    {% for keys, value in url_dict.items %}
         <tr border = 1px black> 
             <th>{{ keys }}</th>
                 <td> {{value.0}}</td>
                 <td> {{value.1}}</td>
         </tr>
    {% endfor %} 
    

    如果列表中可以有任意数量的项目,则只需循环每个项目:

    {% for keys, value in url_dict.items %}
         <tr border = 1px black> 
             <th>{{ keys }}</th>
             {% for eachval in value %}
                 <td> {{ eachval}}</td>
             {% endfor %}
         </tr>
    {% endfor %} 
    

    【讨论】:

      【解决方案3】:

      要访问 django 模板上的数组元素,您必须将它们称为 elem.attribute。

      在你的情况下,value.0 和 value.1。

      {% for keys, value in url_dict.items %}
      <tr border = 1px black> 
          <th>{{ keys }}</th>
          <td>{{ value.0 }}</td>   <!--requires value[0]  but not working -->
          <td>{{ value.1 }}</td>   <!--not working -->
      </tr>
      {% endfor %} 
      

      此页面可能对您有所帮助:How to access array elements in a Django template?

      希望对你有帮助,

      【讨论】:

        猜你喜欢
        • 2021-06-11
        • 2018-11-09
        • 2011-07-12
        • 2019-09-27
        • 2014-11-16
        • 1970-01-01
        • 2018-09-11
        • 2011-02-27
        • 2016-02-29
        相关资源
        最近更新 更多