Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get exactly one element from list in Jinja?

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 %}
like image 417
Daniel Kusy Avatar asked Jul 15 '18 19:07

Daniel Kusy


1 Answers

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 }}
like image 137
Willem Van Onsem Avatar answered Nov 15 '22 01:11

Willem Van Onsem