1

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?

4
  • You could check this: stackoverflow.com/questions/6197499/twig-forgets-array-keys Commented Jan 17, 2012 at 11:50
  • @OptimusCrime I've looked at that, not relevant. Commented Jan 17, 2012 at 11:59
  • You say it does not work. What is happening instead? Commented Jan 17, 2012 at 13:20
  • When I do {{ data.i }}, it is looking for $data['i'], instead of parsing i as the index of the loop and looking for data.2. Commented Jan 17, 2012 at 13:44

1 Answer 1

5

How about this:

{% for i in range(0, limit-1) %}
  {% if data[i] is defined %}
    {{ data[i] }}
  {% endif %}
{% endfor %}
Sign up to request clarification or add additional context in comments.

1 Comment

You can use the .. operator to create a range {% for i in 0..limit-1 %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.