Twig for Loop for Arrays with Keys

Twig for loop for arrays with keys

I found the answer :

{% for key,value in array_path %}
Key : {{ key }}
Value : {{ value }}
{% endfor %}

Twig loop through array

Your second loop attempt was close but the name key doesnt exists on the initial array keys. id, startTime, EndTime, c, service. The name key appears to be nested under c. So you should be able to access it like:

{% for a in TimeInfo %}
The start time is: {{ a.startTime }}
The Name is: {{ a.c.name }} {# notice we access "c" then "name" #}
{% endfor %}

foreach ( $response as $key = $element ) in Twig

Based on your data and the comments, I'm not even sure you'd need the key to solve your problem

{% for item in items if item.url == uri %}
{{ item.count }}
{% endfor %}

demo


EDIT

As of twig 2.10.0 it's deprecated to use an if directly inside the for-statement, now you either place the if inside the block or use the filter filter

{% for item in items %}
{% if item.url == uri %}
{{ item.count }}
{% endif %}
{% endfor %}
{% for item in items|filter(v => v.url == uri) %}
{{ item.count }}
{% endfor %}

Twig for loop from array

dataTable is 0-indexed array and does not have name property. But each of its subarrays has this property, so I suppose you need this code (as data represents each item of datatTable):

<label class="main-name-list-form">{{ data.name }}</label>

Reference array from key in for loop with Twig

How about this:

{% for i in range(0, limit-1) %}
{% if data[i] is defined %}
{{ data[i] }}
{% endif %}
{% endfor %}

How use variable as key in Twig's for loop?

The syntax is fields_vars [ foo ]. I made you an example on a online ifddle

Fiddle: https://twigfiddle.com/tdau2h

{% set fields_vars =["dogs","cats","birds"] %}
{% set foo = 123 %}

{# value #}
{% if foo in fields_vars %}
{{ foo }} is in array {{ fields_vars|join(', ') }}
{% else %}
{{ foo }} is not in array {{ fields_vars|join(', ') }}
{% endif %}

{# key #}
{% if fields_vars[foo] is defined %}
key {{ foo }} is in array {{ fields_vars|join(', ') }}
{% else %}
key {{ foo }} is not in array {{ fields_vars|join(', ') }}
{% endif %}


Related Topics



Leave a reply



Submit