Drupal Добавляет Span внутри тегов в красивые меню
Вопрос
Я пытаюсь добавить выпадающие меню в тему drupal, которая использует CSS-округление текстовых раздвижных дверей.
Текущая версия использует внедрение первичных ссылок span в теги a, что работает нормально.Но не поддерживает выпадающие меню.
Рабочий код:
<?php print theme('links', $primary_links, array('class' => 'links primary-links')) ?>
В шаблоне с template.php дополнение файла :
<?php
// function for injecting spans inside anchors which we need for the theme's rounded corner background images
function strands_guybrush_links($links, $attributes = array('class' => 'links')) {
$output = '';
if (count($links) > 0) {
$output = '<ul'. drupal_attributes($attributes) .'>';
$num_links = count($links);
$i = 1;
foreach ($links as $key => $link) {
$class = $key;
// Add first, last and active classes to the list of links to help out themers.
if ($i == 1) {
$class .= ' first';
}
if ($i == $num_links) {
$class .= ' last';
}
if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))) {
$class .= ' active';
}
$output .= '<li'. drupal_attributes(array('class' => $class)) .'>';
if (isset($link['href'])) {
$link['title'] = '<span class="link">' . check_plain($link['title']) . '</span>';
$link['html'] = TRUE;
// Pass in $link as $options, they share the same keys.
$output .= l($link['title'], $link['href'], $link);
}
else if (!empty($link['title'])) {
// Some links are actually not links, but we wrap these in <span> for adding title and class attributes
if (empty($link['html'])) {
$link['title'] = check_plain($link['title']);
}
$span_attributes = '';
if (isset($link['attributes'])) {
$span_attributes = drupal_attributes($link['attributes']);
}
$output .= '<span'. $span_attributes .'>'. $link['title'] .'</span>';
}
$i++;
$output .= "</li>\n";
}
$output .= '</ul>';
}
return $output;
}
?>
Итак, я добавил Хороший модуль меню который хорошо работает и позволяет выполнять функции выпадающего меню для моей навигации, которая теперь адресуется из шаблона с использованием:
<?php print theme_nice_menu_primary_links() ?>
Проблема в том, что теги a должны иметь промежутки внутри, чтобы обеспечить разметку выбранного состояния.Я перепробовал все, что смог найти, чтобы отредактировать функцию drupal menu_item_link, которая используется nice menu для создания ссылок.
Например.Я просматривал форум drupal в течение двух дней и никакой радости.
Строки в модуле, которые создают ссылки, являются:
function theme_nice_menu_build($menu) {
$output = '';
// Find the active trail and pull out the menus ids.
menu_set_active_menu_name('primary-links');
$trail = menu_get_active_trail('primary-links');
foreach ($trail as $item) {
$trail_ids[] = $item['mlid'];
}
foreach ($menu as $menu_item) {
$mlid = $menu_item['link']['mlid'];
// Check to see if it is a visible menu item.
if ($menu_item['link']['hidden'] == 0) {
// Build class name based on menu path
// e.g. to give each menu item individual style.
// Strip funny symbols.
$clean_path = str_replace(array('http://', '<', '>', '&', '=', '?', ':'), '', $menu_item['link']['href']);
// Convert slashes to dashes.
$clean_path = str_replace('/', '-', $clean_path);
$class = 'menu-path-'. $clean_path;
$class .= in_array($mlid, $trail_ids) ? ' active' : '';
// If it has children build a nice little tree under it.
if ((!empty($menu_item['link']['has_children'])) && (!empty($menu_item['below']))) {
// Keep passing children into the function 'til we get them all.
$children = theme('nice_menu_build', $menu_item['below']);
// Set the class to parent only of children are displayed.
$class .= $children ? ' menuparent ' : '';
// Add an expanded class for items in the menu trail.
$output .= '<li id="menu-'. $mlid .'" class="'. $class .'">'. theme('menu_item_link', $menu_item['link']);
// Build the child UL only if children are displayed for the user.
if ($children) {
$output .= '<ul>';
$output .= $children;
$output .= "</ul>\n";
}
$output .= "</li>\n";
}
else {
$output .= '<li id="menu-'. $mlid .'" class="'. $class .'">'. theme('menu_item_link', $menu_item['link']) .'</li>'."\n";
}
}
}
return $output;
}
Как вы можете видеть, $output использует menu_item_link для разбора массива на ссылки и добавления класса active к выбранной навигационной ссылке.
Вопрос в том, как мне добавить span внутри тегов a или как мне обернуть теги a span, у которого есть активный класс, для оформления ссылок на раздвижные двери?
Решение
Если вы хотите обернуть теги a промежутком, вы можете перезаписать theme_nice_menu_build
и добавьте свой диапазон к выходным данным.Если вы хотите внутри тега a, вам нужно перезаписать menu_item_link
.
Вы можете перезаписать функцию темы, создав вызов функции your_theme_name_function_name
и Drupal будет использовать эту функцию для отображения разметки вместо разметки по умолчанию.Таким образом, вы можете изменить разметку любым удобным для вас способом.Эта функция должна быть в файле вашей темы template.php.
Хороший способ начать - скопировать функцию, которую вы хотите перезаписать, и просто изменить по своему усмотрению.
Со времен Drupal 4.7 многое произошло, я не надеюсь, что вы этим воспользуетесь.Вставить теги span довольно легко:
function your_theme_name_menu_item_link($link) {
if (empty($link['localized_options'])) {
$link['localized_options'] = array();
}
$link['localized_options']['html'] = TRUE;
return l('<span>' . $link['title'] . '</span>', $link['href'], $link['localized_options']);
}
Я протестировал это, и это работает просто отлично.