Drupal文档教程翻译 - 为不同层级的菜单项添加class

logo-drupal-documentation本站原创编译,转载请给面子,尊重劳动果实,欢迎交流指正。

早上好。昨天和老朋友聚了聚,啤酒啊什么的最好喝了,现在还想喝,咖啡啊枸杞啊毒蘑菇啊都去死掉好了。继续啦,Drupal小水珠;昨天的文档里面,我们了解了怎样为主/次级菜单项添加分隔符,今天来看看怎样为导航菜单中不同层级的菜单项添加不同的class。

其实这事挺常见,我们的主要意图是给菜单项中的<a>标签添加class。一如既往,我们可以在template.php文件中做手脚。也可以首先了解一下相关的背景知识比如theme_menu_item_linkl() function这两个API,以及我们之前做过的有关主题覆写方面的一系列文档。

为每一级菜单项添加class

下面的代码可以为每一级菜单项中的<a>标签添加形式为“level-x”的class:

<?php
function phptemplate_menu_item_link($link) {
if (empty($link['localized_options'])) {
$link['localized_options'] = array();
}
$link['localized_options']['attributes']['class'] .= ' level-' . $link['depth'];

return l($link['title'], $link['href'], $link['localized_options']);
}

仅为指定级别的菜单项添加class

假设我们希望为所有深度为1的菜单项添加“first-level”作为class:

<?php
function phptemplate_menu_item_link($link) {
if (empty($link['localized_options'])) {
$link['localized_options'] = array();
}
if ($link['depth'] == 1) { // 1 for first level, 2 for second, etc
$link['localized_options']['attributes']['class'] .= ' first-level'; // change first-level to whatever you'd like to be your class, don't forget the space before.
}
return l($link['title'], $link['href'], $link['localized_options']);
}
?>

为指定名称的菜单中的各级菜单项添加class

需求和第一个差不多,不过在这里我们假设只对名为“my-menu-name”的菜单做手脚:

<?php
function phptemplate_menu_item_link($link) {
if (empty($link['localized_options'])) {
$link['localized_options'] = array();
}
if ($link['menu_name'] == 'my-menu-name') { // change my-menu-name for the name of the menu you want the classes in
$link['localized_options']['attributes']['class'] .= ' level-' . $link['depth'];
}
return l($link['title'], $link['href'], $link['localized_options']);
}
?>

这些是比较常见的需求,其他类似的逻辑我们可以自己继续推敲;通过类似的代码和对phptemplate_menu_item_link函数的打造覆写,我们可以实现更多的具体需求,不一一陈述喽。

译者:Viiiix7210

如需转载,请注明官方英文文档及本人译文的出处,谢谢。查看英文原文: Classes per level of menu items links


收藏与分享

添加评论


Security code
换一张图