📜  twig for loop key - PHP (1)

📅  最后修改于: 2023-12-03 15:35:23.302000             🧑  作者: Mango

Twig For Loop Key - PHP

When working with loops in Twig, it's common to need access to the current iteration key. This is where the key variable comes in handy.

Syntax

To access the loop key in Twig, use the following syntax:

{% for key, value in array %}
    ...
{% endfor %}

Here, key is the variable that will contain the current iteration key, while value is the variable that will contain the current iteration value.

Examples

Let's say we have an array of fruits like this:

$fruits = array(
    'apple' => 'red',
    'banana' => 'yellow',
    'grape' => 'purple'
);

We can loop through this array in Twig and output the key-value pairs like this:

{% for key, value in fruits %}
    The color of the {{ key }} is {{ value }}.
{% endfor %}

This will output:

The color of the apple is red.
The color of the banana is yellow.
The color of the grape is purple.

We can also access the loop key directly in the loop like this:

{% for key, value in fruits %}
    The index of '{{ key }}' is {{ loop.index }}.
{% endfor %}

This will output:

The index of 'apple' is 1.
The index of 'banana' is 2.
The index of 'grape' is 3.

Note that loop.index is the current iteration index, not the key. To access the key, we simply use key.

Conclusion

The key variable is a useful feature in Twig when working with loops. It allows us to easily access the current iteration key and use it in our templates.