Цепочка навигации на основании синонимов URL

07 Ноя 2008
Опубликовано VladSavitsky

Решение

Скрипт читает синоним пути и создает цепочку навигации, которая отображает этот путь. Скрипт проверяет относится ли путь к таксономии или ноде и возвращает соответствующий заголовок. Если нет пути или ноды (например, индексы созданные pathauto), то просто показывается слово или слова как заголовок.

Этот скрипт бесполезен, если вы используете мультиязычность или сайт находится по подпапке веб-сервера. В этих случаях цепочка навигации будет выглядеть примерно так:

  • "Главная > папка в которой находится друпал > [dir]" или
  • "Главная > en > [dir]"

Если скрипт не может найти страницу с таким URL, то выводится просто ссылка на не существующую страницу, а заголовок на английском языке.

В файле page.tpl.php текущей темы нужно добавить код:

<?php print url_breadcrumbs(); ?>

Drupal 6.x

function url_breadcrumb($breadcrumb) {
    $url = path_alias_array();

    // On admin pages, use the default breadcrumb. But I prefer having the
    // title of the current page display as well.  So I remove the '</div>'
    // tag from the original breadcrumb with substr() and add in the title with
    // drupal_get_title().
    if ($url[0] == 'admin')
        return substr($breadcrumb, 0, -6) . ' &raquo; <strong>' . drupal_get_title() . '</strong></div>';

    $output .= '<div class="breadcrumb">';

    // Remove this line if you don't like the Home link.  You'll need to adjust
    // the code below too, to not display ">>" (&raquo;) at the start of the
    // breadcrumb
    $output .= '<a href="' . base_path() . '" title="Home">Home</a>';

    $output .= get_crumb_all();
    $output .= '</div>';

    return $output;
}

// Extract the URL path alias from the URI
function path_alias_array() {

    $uri_request_id = $_SERVER['REQUEST_URI'];
    $urlexplode = explode("?", $uri_request_id);

    if (base_path() != '/') {
        $urlfinal = explode(base_path(), $urlexplode[0]);
        $url = explode("/", $urlfinal[1]);
    }
    else {
        $url = explode("/", $urlexplode[0]);
    }

    return $url;
}

// Get full breadcrumb
function get_crumb_all() {
    $url = path_alias_array();

    // Construct each piece of the breadcrumb
    $numbs = array_keys($url);
    foreach ($numbs as $numb) {
        $crumbs .= get_crumb($numb);
    }
    return $crumbs;
}

// Get breadcrumb piece
function get_crumb($lvl){
    $url = path_alias_array();

    // Reconstruct path alias as string
    for ($i = 0; $i < $lvl+1; $i++) {
        $urlpathalias .= $url[$i];
        if ($i != $lvl)
            $urlpathalias .= '/';
    }
    $urlpathalias = str_replace('%20', ' ', $urlpathalias);

    // If Drupal install is not in a subdir, we need to remove extra '/'
    if ($urlpathalias[0] == '/')
        $urlpathalias = substr($urlpathalias, 1);

    // If at Home, return now so we don't append the '>>'
    if ($urlpathalias == '')
        return;

    // It is assumed that all paths are URL path aliases, so if you go to a
    // page without a path alias, the breadcrumb will not display correctly
    $urlsystem = drupal_lookup_path('source', $urlpathalias);
    $urlsystemexplode = explode("/", $urlsystem);
    $urltype = $urlsystemexplode[0];

    $crumbpiece = ' &raquo; ';

    // Uncomment this if you remove the Home crumb above
    // if ($lvl == 1)
    //     $crumbpiece = ' ';

    if ($urltype == "taxonomy") {
        $term = taxonomy_get_term($urlsystemexplode[2]);
        if ($lvl == count($url)-1) {
            // Set to '' if you don't want to display current page's title
            $crumbpiece =  $crumbpiece . ' <strong>'.$term->name.'</strong>';
        }
        else {
            $crumbpiece =  $crumbpiece . ' <a href="' . base_path() .$urlpathalias.'" title="'.$term->name.'">'.$term->name.'</a>';
        }
    }
    elseif ($urltype == "node") {
        $node = node_load($urlsystemexplode[1]);
        if ($lvl == count($url)-1) {
            // Set to '' if you don't want to display current page's title
            $crumbpiece =  $crumbpiece . ' <strong>'.$node->title.'</strong>';
        }
        else {
            $crumbpiece =  $crumbpiece . ' <a href="' . base_path() . $urlpathalias.'">'.$node->title.'</a>';
        }
    }
    else {
        $urltitleexplode = explode("-", $url[$lvl]);
        $words = array_keys($urltitleexplode);
        foreach ($words as $word){
            $urltitle .= ''.ucwords($urltitleexplode[$word]).' ';
        }
        if ($lvl == count($url)-1) {
            // Set to '' if you don't want to display current page's title
            $crumbpiece =  $crumbpiece . ' <strong>'.$urltitle.'</strong>';
        }
        else {
            $crumbpiece =  $crumbpiece . ' <a href="' . base_path() .$urlpathalias.'" title="'.$urltitle.'">'.$urltitle.'</a>';
        }
    }

    // Deal with underscores before returning
    $crumbpiece = str_replace('_', ' ', $crumbpiece);
    return ucwords($crumbpiece);
}

Drupal 5.x

В файле template.php текущей темы добавить код:

function get_crumb($lvl) {
    $uri_request_id = $_SERVER['REQUEST_URI'];
    $urlexplode = explode("?", $uri_request_id);
    $url = explode("/",$urlexplode[0]);
   
    if($url[$lvl]){
      if($lvl > 1) {
        $var = array_keys($url);
        foreach($var as $vars){
          if($vars == 1){
            $urlpathpeice .= $url[$vars];
          }
          if($vars <= $lvl && $vars > 1){
            $urlpathpeice .= '/'.$url[$vars];
          }
        }
        $urlpathalias = $urlpathpeice;
      } elseif ($lvl == 1) {
        $urlpathalias = $url[$lvl];
      }
      $urlsystem = drupal_lookup_path('source', $urlpathalias);
      $urlsystemexplode = explode("/", $urlsystem);
      $urltype = $urlsystemexplode[0];
   
      if($urltype == "taxonomy"){
        $term = taxonomy_get_term($urlsystemexplode[2]);
        if($url[$lvl+1]){
          return  ' &raquo; <a href="/'.$urlpathalias.'" title="'.$term->name.'">'.$term->name.'</a>';
        } else {
          return  ' &raquo; '.$term->name.'';
        }
      } elseif($urltype == "node"){
        $node = node_load($urlsystemexplode[1]);
        if($url[$lvl+1]){
          return  ' &raquo; <a href="/'.$urlpathalias.'" title="'.$nodename.'">'.$node->title.'</a>';
        } else {
          return  ' &raquo; '.$node->title;
        }
      } else {
        $urltitleexplode = explode("-", $url[$lvl]);
        $words = array_keys($urltitleexplode);
        foreach($words as $word){
          $urltitle .= ''.ucwords($urltitleexplode[$word]).' ';
        }
       
        // Removes trailing whitespace
        $urltitle = trim($urltitle);
        if($url[$lvl+1]) {
          return  ' &raquo; <a href="/'.$urlpathalias.'" title="'.$urltitle.'">'.$urltitle.'</a>';
        } else {
          return  ' &raquo; '.$urltitle.'';
        }
      }
    }
}

function get_crumb_all() {
    $uri_request_id = $_SERVER['REQUEST_URI'];
    $urlexplode = explode("?", $uri_request_id);
    $url = explode("/",$urlexplode[0]);
   
    $numbs = array_keys($url);
    foreach($numbs as $numb) {
      $crumbs .= get_crumb($numb);
    }
    return $crumbs;
}

function url_breadcrumbs() {
    $output .= '';
    $output .= 'Home';
    $output .= get_crumb_all();
    $output .= '';
   
    return $output;
}

Чтобы скрыть "Главная" на главной странице нужно изменить функцию в template.php текущей темы (не работает при мультиязыкности и сайте в подпапке):

function get_crumb_all() {
    $uri_request_id = $_SERVER['REQUEST_URI'];
    $urlexplode = explode("?", $uri_request_id);
    $url = explode("/",$urlexplode[0]);
    $numbs = array_keys($url);
    foreach($numbs as $numb) {
      $crumbs .= get_crumb($numb);
    }
if ($crumbs){
    echo '<a href="/" title="Home">Home</a>';
}
    return $crumbs;
}

Drupal 4.7

В файле template.php текущей темы добавить код:

function url_breadcrumbs() {

  function get_crumb($lvl){

    $uri_request_id = $_SERVER['REQUEST_URI'];
    $urlexplode = explode("?", $uri_request_id);
    $url = explode("/",$urlexplode[0]);

    if($url[$lvl]){
      if($lvl > 1) {
        $var = array_keys($url);
        foreach($var as $vars){
          if($vars == 1){
            $urlpathpeice .= $url[$vars];
          }
          if($vars <= $lvl && $vars > 1){
            $urlpathpeice .= '/'.$url[$vars];
          }
        }
        $urlpathalias = $urlpathpeice;
      } elseif ($lvl == 1) {
        $urlpathalias = $url[$lvl];
      }
      $urlsystem = drupal_lookup_path('source', $urlpathalias);
      $urlsystemexplode = explode("/", $urlsystem);
      $urltype = $urlsystemexplode[0];

      if($urltype == "taxonomy"){
        $term = taxonomy_get_term($urlsystemexplode[2]);
        if($url[$lvl+1]){
          return  ' >> <a href="/'.$urlpathalias.'" title="'.$term->name.'">'.$term->name.'</a>';
        } else {
          return  ' >> '.$term->name.'';
        }
      } elseif($urltype == "node"){
        $node = node_load($urlsystemexplode[1]);
        if($url[$lvl+1]){
          return  ' >> <a href="/'.$urlpathalias.'" title="'.$nodename.'">'.$node->title.'</a>';
        } else {
          return  ' >> '.$node->title;
        }
      } else {
        $urltitleexplode = explode("-", $url[$lvl]);
        $words = array_keys($urltitleexplode);
        foreach($words as $word){
          $urltitle .= ''.ucwords($urltitleexplode[$word]).' ';
        }
        if($url[$lvl+1]) {
          return  ' >> <a href="/'.$urlpathalias.'" title="'.$urltitle.'">'.$urltitle.'</a>';
        } else {
          return  ' >> '.$urltitle.'';
        }
      }
    }
  }

  function get_crumb_all() {
    $uri_request_id = $_SERVER['REQUEST_URI'];
    $urlexplode = explode("?", $uri_request_id);
    $url = explode("/",$urlexplode[0]);

    $numbs = array_keys($url);
    foreach($numbs as $numb) {
      $crumbs .= get_crumb($numb);
    }
  return $crumbs;
  }

  $output .= '<div class="breadcrumb">';
  $output .= '<a href="/" title="Home">Home</a>';
  $output .= get_crumb_all();
  $output .= '</div>';

return $output;
}

Вывод

Полезные рецепты по этой теме

Использованные материалы

Полезные ссылки

 
 
 

RSS-лента новостей

Dries Buytaert по-русски
]]>Русский поиск Drupal]]>

Перенос сайта из Joomla в Drupal
Перенос сайта из WordPress в Drupal

]]> Drupal - это бесплатная система управления контентом с открытым исходным кодом ]]>