Reference List Item by Index Within Django Template

Reference list item by index within Django template?

It looks like {{ data.0 }}. See Variables and lookups.

Reference list items by index Django template

Use the forloop.first variable to determine the first form in the list:

{% for form in forms %}
<div class="{{ forloop.first|yesno:'image,question' }}">
{{ form.as_p }}
</div>
{% endfor %}

P.S. You don't need it for this case but to get the sublist in the template you can use the slice template filter.

Get list item dynamically in django templates

This is not possible directly because Django thinks that "x" is the key to lookup in mylist - instead of the value of x. So, when x = 5, Django tries to look up mylist["x"] instead of mylist[5].

Use the following filter as workaround:

@register.filter
def lookup(d, key):
return d[key]

and use it like

{{ mylist|lookup:x }}

Django - get element index in a list in template

{{forloop.counter}} this is it.
Only add this line before the element



Related Topics



Leave a reply



Submit