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?
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.
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.
{% 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With