简体   繁体   中英

Get index # of array in twig

Trying to output the index # of an array in twig, having trouble finding it in the docs. Anyone know how to get it?

array(2) {
  [0]=>
  array(2) {
    ["testimonial"]=>
    string(18) "Derby Heist Test 1"
    ["author"]=>
    string(6) "test 1"
  }
  [1]=>
  array(2) {
    ["testimonial"]=>
    string(18) "Derby Heist Test 2"
    ["author"]=>
    string(6) "test 2"
  }
}

so I'd like to output the index numbers 0 and 1 in a for loop. Please help.

You can use The loop variable as example:

{% for user in users %}
    {{ loop.index }} - {{ user.username }}
{% endfor %}

loop.index The current iteration of the loop. (1 indexed)

loop.index0 The current iteration of the loop. (0 indexed)

Hope this help

Just foreach through your main array, and specify you want the index:

foreach($array as $index=>$arr) { ...

$index will now give you what you need.

Or via TWIG:

{% for key,value in array_path %}
    Key : {{ key }}
    Value : {{ value }}
{% 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