AddThis

Showing posts with label Drupal 8. Show all posts
Showing posts with label Drupal 8. Show all posts

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 :)

[Drupal 8] Include html tags in link function in twig

It is obvious to have a difficult client, who can ask you to do things that are a bit messy. 

I had to face many such situations while working on different projects. One such situation has inspired me to start writing on Drupal. 

To an extend user experience of a website is dependent on its navigation. Main navigation accounts to a measurable heights in it. In this case, one of the menu item has had a text aligned in italics, eg., About the Organisation. The term Organisation has to be in italics. 

I've started by adding a menu link at Structure -> Menus -> Main navigation, as About the <i>Organisation</i>.

In the template, we are rendering the menu item as,
{{ link(item.title, item.url) }}

Output of the above link will be, About the <i>Organisation</i>. Which is not what we're expecting to show to the visitors. 

To format the html for the above link, pass the raw filter on item.title. This filter is used to format text containing html in the twig file. Later assign the formatted text to a variable, here it is title. At last in link function, replace item.title with title. 
{% set title %}
    {{ item.title|raw }}
{% endset %}
{{ link(title, item.url) }}