Django模板标签:获取字典的键、值

Django template tag: getting key, value of dictionary

我想访问下面字典的键值,并将它们输出到 Django 模板文件中。但是,我无法获得价值。它引发了一个错误。如何访问每个字典 key 及其值(option_nameanswerimg_option)?


词典

{u'options': [{235: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>},
              {236: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>}, 
              {237: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>}, 
              {238: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>}]

  }

Django 模板

{% for key, option in options.items %}
    <tr class="option_row rowRecord" id="{{key}}">
        <td>{{option[key].option_name}}</td>
        <td>{{option[key].img_option}}</td>
        <td>{{option[key].answer}}</td>
        <td><i class="material-icons option-delete">delete</i></td>
    </tr>
{% endfor %}

出现错误

TemplateSyntaxError: Could not parse the remainder: '[0].option_name' from 'option[0].option_name'

肮脏的解决方案(因为你的原始字典有嵌套列表和字典):

{% for key, values in options.items %}
    {% for value in values %}
        {% for k, v in value.items %}
            key = {{ k }}
            val = {{ v }}
        {% endfor %}
    {% endfor %}
{% endfor %}

更好的解决方案:

您应该考虑将字典扁平化,以便更容易循环。您不需要嵌套列表和字典。示例:

options = {
    235: <Option ...>,
    236: <Option ...>,
    237: <Option ...>,
    238: <Option ...>,
}

现在,您将能够在一个循环中遍历它。