This may be simple, but I looked around and couldn't find an answer. What's the best way to reference a single item in a list from a Django template?
In other words, how do I do the equivalent of {{ data[0] }}
within the template language?
The slice filter returns the specified items from a list. You can define the from (inlcuded) and to (not included) indexes. If you use negative indexes, it means slicing from the end of the list, -1 refers to the last item, -2 refers to the second last item etc.
These are special tokens that appear in django templates. You can read more about the syntax at the django template language reference in the documentation. {{ foo }} - this is a placeholder in the template, for the variable foo that is passed to the template from a view.
Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.
{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.
It looks like {{ data.0 }}
. See Variables and lookups.
A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
such as get my_list[x] in templates:
in template
{% load index %}
{{ my_list|index:x }}
templatetags/index.py
from django import template
register = template.Library()
@register.filter
def index(indexable, i):
return indexable[i]
if my_list = [['a','b','c'], ['d','e','f']]
, you can use {{ my_list|index:x|index:y }}
in template to get my_list[x][y]
It works fine with "for"
{{ my_list|index:forloop.counter0 }}
Tested and works well ^_^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With