Reputation: 14798
In Twig I am trying to iterate over a potentially incomplete array using a fixed-length for loop so I can show what values are empty.
In PHP this would be simplified to:
for($i =0; $i <= $limit; $i++) {
if($data[$i]) {
echo $data[$i];
}
)
The only thing is that in Twig I am having problems using the key (index) of the loop to reference a value in an array, this is what I've tried and expected to work, but doesn't:
{% for i in range(0, limit-1) %}
{{ data.i }}
{% endfor %}
I could obviously use array_pad()
to pad out my array in my controller, but surely there must be a way to do this in twig?
Upvotes: 1
Views: 4015
Reputation: 34107
How about this:
{% for i in range(0, limit-1) %}
{% if data[i] is defined %}
{{ data[i] }}
{% endif %}
{% endfor %}
Upvotes: 5