2014-09-22 65 views
2

如何使用Twig創建導航菜單?請注意,我沒有使用Sympony2。使用Twig創建導航菜單

給出下面的數組傳遞到樹枝模板:

$menu_main=array(
    'active'=>2, 
    'menu'=>array(
     array('components_id'=>2,'name'=>'First Link','newwindow'=>0), 
     array('components_id'=>3,'name'=>'Second Link','newwindow'=>0), 
     array('components_id'=>7,'name'=>'Third Link','newwindow'=>1), 
     array('components_id'=>8,'name'=>'Forth Link','newwindow'=>0) 
    ) 
); 

我試圖創建下面的導航菜單:

<ul> 
    <li class="first active"><a href="index.php?cid=2">First Link</a></li> 
    <li><a href="index.php?cid=3">Second Link</a></li> 
    <li><a href="index.php?cid=7" target="_blank">Third Link</a></li> 
    <li class="last"><a href="index.php?cid=8">Forth Link</a></li> 
</ul> 

下面是我的非工作的嘗試:

{# 
menu_main is an associated array containing active key and menu key. 
menu is an associated array of containing name, components_id, and whether it should open a new window 
#} 
<ul> 
    {% for item in menu_main.menu %} 
    <li 
    {% if item.components_id == menu_main.active %} 
    class="active" 
    {# How do I add first and last class? Maybe using length? #} 
    {% endif%}> 
    <a href="{{ item[0] }}">{{item[1]}}{% if item.newwindow %} target="_blank" {% endif%}></a> 
    </li> 
    {% endfor %} 
</ul> 

回答

2

這應該適合你。 作爲$ MAIN_MENU [ '菜單']數組是締枝杈不會明白項[0]或[1]

{# 
menu_main is an associated array containing active key and menu key. 
menu is an associated array of containing name, components_id, and whether it should open a new window 
#} 
<ul> 
    {% for item in menu_main.menu %} 
    {% set classes = "" %} 
    <li 
    {% if item.components_id == menu_main.active %} 
     {% set classes = classes~' active ' %} 
    {% endif%}> 
    {% if loop.first %} 
     {% set classes = classes~' first ' %} 
    {% elseif loop.last %} 
     {% set classes = classes~' last ' %} 
    {% endif %} 
    <a class="{{ classes }}" href="index.php?cid={{ item['components_id'] }}">{{item['name']}}</a> 
    </li> 
    {% endfor %} 
</ul> 
+0

疑難雜症關於相關聯的陣列。加入「第一個」和「最後一個」類名怎麼樣?這隻會添加「主動」類。 – user1032531 2014-09-22 20:22:42

+0

您可以在循環內使用'loop.first'和'loop.last'。我將編輯它的答案。 – yajakass 2014-09-22 20:24:54

+0

謝謝!剛開始使用Twig。我喜歡它:)但是有這麼多我還不知道:( – user1032531 2014-09-22 20:26:05