2015-09-25 88 views
1

我目前通過php(樹枝模板)迭代數據數組。在php,twig中從循環迭代中提取整數

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

數據只是文字。是否有可能同時得到一個整數來更新數組索引:

typeDefEvent[i] 

? 謝謝並記住,這是一個樹枝模板。

回答

0
{% 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 %} 

基本設置和使用模板標籤

2

有沒有必要在這裏介紹的另一個變量更新循環迭代。引用the docs:一個for循環塊的

在裏面你可以訪問一些特殊的變量:

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 

所以,你可以寫你的模板是這樣的:

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

好極了,謝謝獲取信息 – Ryan