2014-01-21 19 views
1

我使用的是Symfony 2.3和Twig 1.15。我有一個嵌套的foreach樹枝循環,我試圖爲外循環的最後一次迭代獲得不同的結果。樹枝上錯誤的父環路上下文

我已經看到了這一點:http://twig.sensiolabs.org/doc/recipes.html#accessing-the-parent-context-in-nested-loops 但是我得到了不同的結果 - 一個錯誤在我訪問父上下文行:

Key "loop" for array with keys "groups, scores, type, user, assetic, app, avatarsDir, sonata_block, _parent, _seq, group, _key, subgroup" does not exist in "(...)" 

相關的代碼,剝去類,IDS和不必要的標籤:

{% for group in groups %} 
    <div> 
     {% for subgroup in group.subgroups %} 
      {% for test in subgroup.tests %} 
       {% block test_block_box %} 
        {% if not loop.parent.loop.last %} 

         (html follows...) 

        {% else %} 

         (some different html follows...) 

        {% endif %} 
       {% endblock %} 
      {% endfor %} 
     {% endfor %} 
    </div> 
{% endfor %} 

我已經確定了錯誤不是指內環呼叫,即我換成loop.parent.loop.lastloop.last和頁面渲染成功(內容顯然是錯誤的,但它沒有崩潰)。

當我訪問父上下文時,我做錯了什麼?

+2

你能在循環,不{%塊%}嘗試一下呢?也許Twig在確定塊中的父項時遇到問題。 –

+1

是的,這解決了這個問題。顯然,塊指令改變了Twig的上下文。任何想法,如果這是預期的行爲? –

回答

0

只需刪除{% block test_block_box %}{% endblock %},循環父母應該可以訪問。

你可以嘗試定義的值{% block %}之外,看看您是否可以訪問它在{% block %}

{% for group in groups %} 
    <div> 
     {% for subgroup in group.subgroups %} 
      {% for test in subgroup.tests %} 
       {% set test_loop_is_last = loop.last %} {# define the value #} 
       {% block test_block_box %} 
        {% if not test_loop_is_last %}{#test the value #} 

         (html follows...) 

        {% else %} 

         (some different html follows...) 

        {% endif %} 
       {% endblock %} 
      {% endfor %} 
     {% endfor %} 
    </div> 
{% endfor %} 
+0

這就是我最終做的。非常感謝 :) –