Louie Miranda
Louie Miranda

Reputation: 1159

Year loop on twig

I have the following PHP code that generates current year, and loops it until it reaches the 10th year.

<?php for ($i=date('Y'); $i <= date('Y', strtotime('+10 years')); $i++) : ?>
<option value="<?php echo $i; ?>"
<?php endfor; ?>

I an new on twig, and would like to ask for assistance on how to make it.

Upvotes: 0

Views: 1733

Answers (2)

RZ-DEV
RZ-DEV

Reputation: 11

Another approach from the twig documentation

{% set start_year = date() | date('Y') %}
{% set end_year = start_year + 5 %}

{% for year in start_year..end_year %}
    {{ cycle(['odd', 'even'], loop.index0) }}
{% endfor %}

https://twig.symfony.com/doc/3.x/functions/cycle.html

Upvotes: 1

Donald P
Donald P

Reputation: 853

Here's a couple options using lists, can repurpose pretty easily for an option...

    <ul>
        {% for i in "now"|date("Y").."now +10 years"|date("Y") %}
        <li>{{  ("now +"~(loop.index-1)~" years")|date("Y") }}</li>
        {% endfor %}
    </ul>

    {% set minYear = "now"|date("Y") %}
    {% set maxYear = "now +10 years"|date("Y") %}
    <ul>
        {% for year in minYear..maxYear %}
        <li>{{ year }}</li>
        {% set year = year + 1 %}
        {% endfor %}
    </ul>

Upvotes: 6

Related Questions