Question

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?

Was it helpful?

Solution

How about this:

{% for i in range(0, limit-1) %}
  {% if data[i] is defined %}
    {{ data[i] }}
  {% endif %}
{% endfor %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top