1

I want to build a dynamic html select element that includes the prior five years, given the current year. So, since it is now 2020, the result would be:

<select>
<option value="2015">2015</option>
.
.
<option value="2019">2019</option>

Basically want a "loop while" function, but Twig does not do that. I know I did something like this once before with a macro, but can't for the life of me remember and can't find anything on Stack Exchange.

I know I could do it with Javascript, but would prefer to use Twig. Have the feeling I am missing something obvious, just not obvious to me!

2

You can do something like this (with lots of refactoring possible):

{% set thisYear = now | date("Y") %}
{% set startYear = thisYear - 1 %}
{% set endYear = startYear - 4 %}

{% set yearRange = startYear..endYear %}

<select name="">
{% for year in yearRange %}
    <option value="{{ year }}">{{ year }}</option>
{% endfor %}
</select>
| improve this answer | |
  • It's also simple enough to build this into a macro where you pass in the start year and the number of years back you want it to go. Or the start year and end year You can then build the range and iterate over it. – Mijingo Jan 12 at 21:16
  • You can also do the range right in the for-loop, too. {% for year in startYear..endYear %} – Mijingo Jan 12 at 21:35
  • Thanks, Ryan! {% set yearRange = startYear..endYear %} is what I trying to figure out!! Much appreciated! – Roi Agneta Jan 12 at 22:25
  • A quick video on how to do it for those who like to watch and follow: craftquest.io/lessons/creating-a-dynamic-select-element – Mijingo Jan 14 at 2:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.