Reputation: 343
So I passed a render with directory as an argument in my views.py. Something like this:
def foo(request):
return render(request, 'webapp/foo.html', {'key': ['one', 'two', 'three']})
Now i want to use Jinja in my HTML file to get exactly one element from directory value, let's say first. All I know for know is how to get all elements with for loop:
{% block content %}
{% for val in key %}
<p> {{ val }} </p>
{% endfor %}
{% endblock %}
My question is if is there something like this?
{% block content %}
<p> {{ key[0] }} </p>
{% endblock %}
Upvotes: 7
Views: 26562
Reputation: 133
You can indirectly index list
A string variable can be split into a list by using the split function (it can contain similar values, set is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.
{% set list1 = variable1.split(';') %} The grass is {{ list1[0] }} and the boat is {{ list1[1] }} or
{% set list1 = variable1.split(';') %}
{% for item in list1 %}
<p>{{ item }}<p/>
{% endfor %}
or
{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}
Upvotes: 1
Reputation: 477309
Yes. In Jinja like the documentation says, you can. Such indexing is not supported in Django templates, although using different syntax it can be achieved. You can access the key from an element by using index notation, so:
{{ key[0] }}
But in fact in Django templates you can perform an index lookup as well, with:
{{ key.0 }}
Upvotes: 11