gpt4 book ai didi

php - 使用 Twig 创建导航菜单

转载 作者:行者123 更新时间:2023-11-27 23:52:43 24 4
gpt4 key购买 nike

如何使用 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>

最佳答案

这应该适合您。由于 $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>

关于php - 使用 Twig 创建导航菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25982404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com