如何在drupal主菜单的锚标签中添加唯一ID

时间:2013-10-14 19:32:10

标签: drupal

我是drupal的新手,想在以下方法中添加drupal主菜单的锚标签中的唯一ID, 假设我有一个页面“websiteurl / team” 我希望锚标记为

<a id="team" href="/team">Team</a>

我正在使用此代码显示drupal的主菜单。

<div<?php print $attributes; ?>>
  <div<?php print $content_attributes; ?>>
    <?php if ($main_menu || $secondary_menu): ?>
    <nav class="navigation">
      <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix', 'main-menu')), 'heading' => array('text' => t('Main menu'),'level' => 'h2','class' => array('element-invisible')))); ?>
      <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => array('links', 'inline', 'clearfix', 'secondary-menu')), 'heading' => array('text' => t('Secondary menu'),'level' => 'h2','class' => array('element-invisible')))); ?>
    </nav>
    <?php endif; ?>
    <?php print $content; ?>
  </div>
</div>

请告诉我这是怎么可能的

1 个答案:

答案 0 :(得分:1)

您可以在主题的Drupal部分的preprocess_links钩子中执行此操作。下面是一些示例代码,它使用超链接文本生成唯一ID。如果ID已经存在,它只会将 - {%d}(增量数字)附加到ID值。

在您的有效主题的template.php内。

function YOURTHEME_preprocess_links(&$variables)
{
    // Verify if an ID exist on the links wrapper
    if (!isset($variables['attributes']['id'])) {
        return false;
    }

    // Only generate ID's on the Main Menu
    if ($variables['attributes']['id'] !== 'main-menu') {
        return false;
    }

    // Array holding the generated ID's
    $ids = array();
    foreach ($variables['links'] as &$link) {
        // Loop throug each link and generate unique ID
        $link['attributes']['id'] = _YOURTHEME_generate_unique_id($link['title'], $ids);
    }
}

// Generate unique ID, recursive call when ID already exists
function _YOURTHEME_generate_unique_id($id, &$haystack, $index = 0)
{
    $slug = _YOURTHEME_slugify($id);

    if (in_array($slug, $haystack)) {
        return _YOURTHEME_generate_unique_id(
            sprintf('%s %d', $id, ++$index), $haystack, $index);
    }

    $haystack[] = $slug;

    return $slug;
}

// Generate a 'slug' based on a given string value
function _YOURTHEME_slugify($text)
{
    // Replace non letter or digits by -
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);

    // Trim
    $text = trim($text, '-');

    // Transliterate
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

    // Lowercase
    $text = strtolower($text);

    // Remove unwanted characters
    $text = preg_replace('~[^-\w]+~', '', $text);

    if (empty($text)) {
        return 'n-a';
    }

    return $text;
}

不要忘记清除缓存,以便考虑YOURTHEME_preprocess_links

相关问题