获取Django模板中的列表值

pan*_*ore 3 django django-templates

在视图中:

return render_to_response('template.html',
                          {'headers': list(sort_headers.headers()) },
                          context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

在模板中:

{{ headers }}
<br />
{{ headers|slice:"1" }}
Run Code Online (Sandbox Code Playgroud)

在浏览器中:

[{'url': '?ot=desc&amp;o=0', 'text': 'Nombre', 'class_attr': ' class="sorted ascending"', 'sortable': True}, {'url': '?ot=asc&amp;o=1', 'text': 'Valor', 'class_attr': '', 'sortable': True}, {'url': '?ot=asc&amp;o=2', 'text': 'Inventario', 'class_attr': '', 'sortable': False}, {'url': '?ot=asc&amp;o=3', 'text': 'Fecha Creacion', 'class_attr': '', 'sortable': True}]

[{'url': '?ot=desc&amp;o=0', 'text': 'Nombre', 'class_attr': ' class="sorted ascending"', 'sortable': True}]
Run Code Online (Sandbox Code Playgroud)

我得到一个列表节点{{ headers|slice:"1" }},但现在,如何获得一个dict值?例如'url'返回'?ot=desc&amp;o=0'.

注意:不能使用{% for %}.

dij*_*tra 7

{{headers.1.url}}

来自http://docs.djangoproject.com/en/dev/topics/templates/#variables:

Technically, when the template system encounters a dot, it tries the following lookups, in this order:
    * Dictionary lookup
    * Attribute lookup
    * Method call
    * List-index lookup

因此,您可以执行{{headers.1}}}而不是{{headers | slice:"1"}}.然后要访问网址密钥,您只需附加它:{{headers.1.url}}.

HTH.