k0oda
k0oda

Reputation: 71

Get element of list by variable in Django template

I have line of code in Django template:

<h4>{{ totals.date.weekday }}</h4>

Totals is the Python list, how do i get item of this list by index stored in date.weekday?

This would look in Python like this:

totals[date.weekday]

Creating another variable, which stores date.weekday doesn't work

UPD:

I found a solution:

Just added element of totals list to template context in render

For example:

# ... 
return render(request, 'template.html', context={'date_total'=totals[date.weekday()]})

Upvotes: 0

Views: 2070

Answers (2)

NVS
NVS

Reputation: 401

You have to run the "for loop" for this.

{% with counts = 0 %}
{% while counts < totals.count %}
      {% if counts == date.weekday %}
           <h4>total.counts</h4>
      {% endif %}
      {% counts += 1 %}
{% endfor %}

I did not get your question completely but i think it might help.

Upvotes: -1

NicoT
NicoT

Reputation: 341

You can access the array directly using

{{ totals.0.date.weekday}} where the 0 is the position that you want.

Also if you want to print all the elements in total you will need a for loop such as:

{% for d in totals %}
   {{ d }}
{% endfor %}

about sorting, you can use the pipe order_by but I recommend you to pass the list already ordered from the views

Upvotes: 2

Related Questions