AddThis

Wednesday 15 March 2017

[Drupal 8] Modify the breadcrumb text

Breadcrumbs are considered as a secondary navigation, as it let the user know the current, as well as the path through to the location.

In Drupal 8, Menu breadcrumb is used to set breadcrumbs for the pages. In one of the websites I was working on had sub menu's with html tags. For the About menu, the sub menu was as 'All about Organisation'Menu breadcrumb would show the breadcrumb for the page, 'All about Organisation' as,
 

Home > About > All about <i>Organisation</i>


The breadcrumb is not presentable to the visitor, without stripping or by formatting the html tags. 

To do this, we need to implement hook_preprocess_breadcrumb().


function test_preprocess_breadcrumb(&$variables) {
    foreach ($variables['breadcrumb'] as $key => &$value) {
      $value['text'] = strip_tags($value['text']);
    }
  }

In the hook, $variables['breadcrumb'] contains the details of breadcrumb. 
In our case, there would be three key value pairs($key, $value), first for Home, second for About, and the last one for All about <i>Organisation</i>. Each value contains an array of text($value['text']) and url($value['url']) of each level. By iterating through the key value pair, we strip the tags from Home, About and All about <i>Organisation</i>, which will result in the below breadcrumb.

Home > About > All about Organisation

We've made a presentable breadcrumb for the visitor and that is it.  I would be glad to hear if it helped you. Happy Coding :)

No comments:

Post a Comment