firestoke
firestoke

Reputation: 1059

Django Template: How to modify the value in the for-loop tag?

What I want to do is simple: I want to display a HTML select tag which includes option tags with value 1971 ~ 2020.

The following is code snippet:

Year<select name="selected_year">
{% for i in "x"|rjust:"50" %}
    <option value="{{ forloop.counter }}">{{ forloop.counter }}</option>
{% endfor %}
</select>

the {{forloop.counter}} will display 1 ~ 50.
my question is: how to display 1971 ~ 2020 instead?
any suggestion?

BTW, the for loop code is referenced from another question: Numeric for loop in Django templates

Upvotes: 0

Views: 874

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600059

You could use the |add filter to modify each value:

<option value="{{ forloop.counter|add:1970 }}">{{ forloop.counter|add:1970 }}</option>

But don't do this. Use range(1971, 2021) in the view and pass that to the template.

Upvotes: 2

Related Questions