简体   繁体   中英

Is it possible to concatenate a variable to an if statement in Twig?

I am trying to concatenate a variable to an array key to get access to certain values in Twig, but no success so far.

I have a large PHP array that has for example keys like this:

$array = [
   ...
   ...
   ...
   'test_1' => $test_1,
   'test_2' => $test_2
];

I tried the following in my Twig template:

{% for i in 1..2 %}

   {% if array.test_{{ i }} != 0 %}
      <div>Test</div>
   {% endif %}

{% endfor %}

but that doesn't work.

Is there a way to access values like this in Twig?

Try this:

{% for i in 1..2 %}
    {% if array['test_' ~ i] != 0 %}
        <div>Test</div>
    {% endif %}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM