【问题标题】:Iterate list of dics in template迭代模板中的dict列表
【发布时间】:2013-12-10 07:44:48
【问题描述】:

clients_list

   {'clients': [
    {'id': 357995, 'value': 1.0}, 
    {'id': 369743, 'value': 0.9}
    ]}

{% try %}
{% if clients_list %}
{% for client in clients_list %}
    {% for user in client %}
        {% raw user.id %}
        {% raw user.value %}
    {% end %}
{% end %}
{% end %}
{% except %}
{% end %}

预期输出:

357995
1.0

369743
0.9

问题是模板中的循环是错误的。如何访问 id 和 value?

这是一个龙卷风模板,但我认为它类似于 django。

更新:

{% try %}
{% if clients_list %}
{% for client in clients_list %}
    {% raw client %} // outputs the clients_list
    {% for user in client %}
        {% raw user %} outputs 'clients'
    {% end %}
{% end %}
{% end %}
{% except %}
{% end %}

【问题讨论】:

  • 实际输出是多少?
  • @kroolik 如果我首先执行 {% raw client %},我会得到包含所有数据的 clients_list。在第二个输出中,{% raw user.id %} 和 {% raw user.value %}
  • 所以clients_list 是一个字典列表{'clients': [...]}?
  • @kroolik 是的,正如我在标题中所说的那样。谢谢:)
  • {% for user in client %} 更改为{% for user in client.clients %} 时的输出是什么?

标签: python templates django-templates tornado


【解决方案1】:

这是解决方案。

{% try %}
{% if clients_list %}
{% for client in clients_list %}
    {% for user in client['clients'] %}
        {% raw user['id'] %}
        {% raw user['value'] %}
    {% end %}
{% end %}
{% end %}
{% except %}
{% end %}

【讨论】: