Twig 2.0 年阵列
Twig 2.0 Year Array
我有一个使用 Twig 2.0 的 Set 和 For 语句,但在生成 2020-2070 年数组时遇到了问题。它生成 50 个选项,但选项是从 0-50 而不是 2020-2070。这是我的代码:
{% set start_year = "now"|date('Y') %}
{% set end_year = start_year + 50 %}
{% for year in start_year..end_year %}
<option value="{{ loop.index0}}">{{ loop.index0 }}</option>
您需要显示 year
变量,而不是 loop.index0
即:
The current iteration of the loop. (0 indexed)
来源:https://twig.symfony.com/doc/3.x/tags/for.html#the-loop-variable
所以:
{% for year in "now"|date('Y').."now"|date('Y')+50 -%}
<option value="{{ year }}">{{ year }}</option>
{% endfor %}
渲染:
<option value="2020">2020</option>
<option value="2021">2021</option>
<!-- cut for brevity -->
<option value="2069">2069</option>
<option value="2070">2070</option>
Fiddle: https://twigfiddle.com/ee0fiz
我有一个使用 Twig 2.0 的 Set 和 For 语句,但在生成 2020-2070 年数组时遇到了问题。它生成 50 个选项,但选项是从 0-50 而不是 2020-2070。这是我的代码:
{% set start_year = "now"|date('Y') %}
{% set end_year = start_year + 50 %}
{% for year in start_year..end_year %}
<option value="{{ loop.index0}}">{{ loop.index0 }}</option>
您需要显示 year
变量,而不是 loop.index0
即:
The current iteration of the loop. (0 indexed)
来源:https://twig.symfony.com/doc/3.x/tags/for.html#the-loop-variable
所以:
{% for year in "now"|date('Y').."now"|date('Y')+50 -%}
<option value="{{ year }}">{{ year }}</option>
{% endfor %}
渲染:
<option value="2020">2020</option>
<option value="2021">2021</option>
<!-- cut for brevity -->
<option value="2069">2069</option>
<option value="2070">2070</option>
Fiddle: https://twigfiddle.com/ee0fiz