AddThis

Wednesday 15 March 2017

[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) }}

No comments:

Post a Comment