0

I am tryin creating a drop down list to select a year. The list has to goto 200 years in the past starting from today. I am unable to make a loop work in jinja to create the select options. I have passed it the now variable which holds current year(2020).

The line now -= 1 is thowing me eror: jinja2.exceptions.TemplateSyntaxError

<select class = "year" name = "year">
    {% for x in range (200) %}
        <option value= '{{ now }}'>{{ now }}</option>
        {% now -= 1 %}
    {% endfor %}
</select>

In php I would do this and it works:

<?php
    $curr_date = date('Y');
    for ($i = $curr_date; $i > 1800; $i--) {
        echo '<option value = "' . $i . '">' . $i . '</option>';
    }
?>
amars
  • 407
  • 6
  • 15
  • 1
    Besides using [`set`](https://jinja.palletsprojects.com/en/2.11.x/templates/#assignments). Apparently, assigning to a variable in a loop is a known limitation, as explained [here](https://stackoverflow.com/q/7537439/770830) and [here](https://stackoverflow.com/a/4880398/770830). – bereal Jun 30 '20 at 09:40

1 Answers1

2

You can use the 0-indexed loop index variable for this task: loop.index0:

<select class="year" name="year">
    {% for x in range (200) %}
        <option value= '{{ now - loop.index0 }}'>{{ now - loop.index0 }}</option>
    {% endfor %}
</select>
Dauros
  • 9,294
  • 2
  • 20
  • 28
  • Thanks. That worked. I have not used Django. Only on Flask for now. Would you know if this same limitation exist in Django too? – amars Jun 30 '20 at 09:55
  • In general, Jinja2 is more powerful than Django Templates. The `set` function is not available in Django (but there's a `{% with var="something" %}{% endwith %}` block which is somewhat similar.) However you can define a [custom template filter](https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/), e.g. `subtract` and use it inside the loop to achieve the same behavior: `{{ now|subtract:forloop.counter0 }}`. The `forloop.counter0` is the same loop index like Jinja2's `loop.index0`. – Dauros Jun 30 '20 at 10:57