Tuesday, September 24, 2019

How do you implement a breadcrumb?




Drupal:8 You can use this code it's worked for me. Then the MYTHEME.theme file
<?php    

 use Drupal\Core\Cache;

/**  
* Implements hook_preprocess_breadcrumb().  
*/   
function themename_preprocess_breadcrumb(&$variables){
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
  $variables['#cache']['contexts'][] = 'url';
 if(!empty($node = \Drupal::routeMatch()->getParameter('node'))){
 $variables['breadcrumb'][] = array(
  'text' => $node->getTitle() 
 );
  }
  else{
      $variables['breadcrumb'][] = array(
     'text' => $page_title 
    );
  }
}
}And then create another file in your theme's template folder named as "breadcrumb.html.twig" and put below code in this file :
{% if breadcrumb %}

    <nav class="breadcrumb" role="navigation" aria-labelledby="system-breadcrumb">
        <h2 id="system-breadcrumb" class="visually-hidden">{{ 'Breadcrumb'|t }}</h2>
            {% for item in breadcrumb %}
                    {% if item.url %}
                            <a href="{{ item.url }}">{{ item.text }}</a>
                              <span class="breadcrub_symbole"> > </span>
                    {% else %}
                        <a href="{{ item.url }}">{{ item.text }}</a>
                    {% endif %}            

            {% endfor %}

    </nav>
{% endif %}
Thats it. Now Clear cache and you will get breadcrumb with current page title like Home > Current Page Title. You can change the separator by replacing ">" (on class="breadcrub_symbole" )with the desired one.

No comments:

Post a Comment

If you have any problem please let me know.