Get list values ​​in a Django template

In sight:

return render_to_response('template.html',
                          {'headers': list(sort_headers.headers()) },
                          context_instance=RequestContext(request))

In the template:

{{ headers }}
<br />
{{ headers|slice:"1" }}

In browser:

[{'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}]

I get a list with node c {{ headers|slice:"1" }}, but now, how to get the dict value? for example, 'url' returns '?ot=desc&amp;o=0'.

Note: Do not use {% for %}.

+3
source share
3 answers

{{headers.1.url}}

From 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 | slice: "1" }} {{headers.1}}. , url, : {{headers.1.url}}.

.

+7

, , dict , .

{{dict.items}}, (, ), tuple.1.

{{dict.values}}, .

0

I think you want:

{% with headers|slice:"1" as data %}
<a href="{{ data.url }}"{{ data.class_attr|safe }}>{{ data.text }}</a>
{% endwith %}
-1
source

Source: https://habr.com/ru/post/1718852/


All Articles