Ryan
Ryan

Reputation: 354

Extracting integer from a for loop iteration in php, twig

I am currently iterating through arrays of data in php (twig template).

{% for subscription in form.peerEventSubscriptions %}
<option value='{{typeDefEvent[0]}}'>-{{ form_label(subscription.eventTypeHumanized) }}-</option>
{% endfor %}

The data is just text. Is it possible to also simultaneously get an integer to update the array index:

typeDefEvent[i]

? Thanks and remember, this is a twig template.

Upvotes: 2

Views: 720

Answers (2)

raina77ow
raina77ow

Reputation: 106395

There's no need to introduce another variable here. Quoting the docs:

Inside of a for loop block you can access some special variables:

Variable        Description
loop.index      The current iteration of the loop. (1 indexed)
loop.index0     The current iteration of the loop. (0 indexed)
loop.revindex   The number of iterations from the end of the loop (1 indexed)
loop.revindex0  The number of iterations from the end of the loop (0 indexed)
loop.first      True if first iteration
loop.last       True if last iteration
loop.length     The number of items in the sequence
loop.parent     The parent context

So you can write your template like this:

{% for subscription in form.peerEventSubscriptions %}
  <option value='{{typeDefEvent[loop.index0]}}'>-{{ form_label(subscription.eventTypeHumanized) }}-</option>
{% endfor %}

Upvotes: 3

Ryan
Ryan

Reputation: 354

{% set i = 0 %}
   <select name="myPostVar">
{% for subscription in form.peerEventSubscriptions%}
<option value='{{typeDefEvent[i]}}'>-{{ form_label(subscription.eventTypeHumanized) }}-</option>
{% set i = i+1 %}
{% endfor %}

basically set and update the iterator in the loop using template tags

Upvotes: 0

Related Questions