Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig loop index into array

I want to show my string value into my array 'nameComments' with key {{loop.index}} of my comments array, but {{ nameComments[{{ loop.index }}] }} show an error

{% for com in comments %}
    <p>Comment {{ nameComments[{{ loop.index }}] }} : "{{ com['comment'] }}"</p>
{% endfor %}

If I try:

{% for com in comments %}
    <p>Comment {{ nameComments[1] }} : "{{ com['comment'] }}"</p>
{% endfor %}

And the {{ loop.index }} show me value : 1

So how can I implement my loop index into my array?

like image 869
keegzer Avatar asked Jul 08 '13 10:07

keegzer


People also ask

How do you comment on twig?

To comment out one or more lines of code (or part of a line) use the the {# #} syntax. comment. Comments aren't just useful for writing notes about your code.

Is empty in twig?

Support for the __toString() magic method has been added in Twig 2.3. empty checks if a variable is an empty string, an empty array, an empty hash, exactly false , or exactly null . For objects that implement the Countable interface, empty will check the return value of the count() method.


2 Answers

{% for com in comments %}
    <p>Comment {{ nameComments[ loop.index ] }} : "{{ com['comment'] }}"</p>
{% endfor %}

Just leave out the curly brackets. This should work fine. By the way loop.index is 1 indexed. If you loop through an array which normally starts with index 0 you should consider using loop.index0

See the documentation

like image 195
SirDerpington Avatar answered Oct 07 '22 19:10

SirDerpington


It is safer to iterate over the real value of the array index and not using loop.index and loop.index0 in case where array indexes do not start in 1 or 0 or do not follow a sequence, or they are not integers.

To do so, just try this:

{% for key,com in comments %}
    <p>Comment {{ nameComments[key] }} : "{{ com['comment'] }}"</p>
{% endfor %}

See the documentation

like image 6
Abraham Covelo Avatar answered Oct 07 '22 21:10

Abraham Covelo