如何使用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>
答案 0 :(得分:2)
这对你有用。 由于$ main_menu ['menu']数组是关联的,因此twig不会理解item [0]或item [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>