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!

1 Answer 1

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>
4
  • 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.
    – CraftQuest
    Jan 12, 2020 at 21:16
  • You can also do the range right in the for-loop, too. {% for year in startYear..endYear %}
    – CraftQuest
    Jan 12, 2020 at 21:35
  • Thanks, Ryan! {% set yearRange = startYear..endYear %} is what I trying to figure out!! Much appreciated!
    – Roi Agneta
    Jan 12, 2020 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
    – CraftQuest
    Jan 14, 2020 at 2:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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