Show the link title/description in Twig template on Drupal 8

Show the link title/description in Twig template on Drupal 8

We wanted to actually display the link’s description tag on the page but couldn’t find a way to do it.

We were using {{ link(item.title, item.url) }} to render a link but we couldn’t get the title tag to show up in a Twig variable. Eventually with the use of {{ kint(item) }} and searching through the stack we found out how to get it:

{{ item.original_link.getDescription() }}

It is defined here: web/core/modules/menu_link_content/src/Entity/MenuLinkContent.php in getPluginDefinition() function

It should be in this file: web/core/lib/Drupal/Core/Menu/MenuLinkTree.php in the buildItems() function alongside the other things you would need in a link:

$element['attributes'] = new Attribute();
$element['title'] = $link->getTitle();
$element['url'] = $link->getUrlObject();
$element['url']->setOption('set_active_class', TRUE);
$element['below'] = $data->subtree ? $this->buildItems($data->subtree, $tree_access_cacheability, $tree_link_cacheability) : array();
if (isset($data->options)) {
$element['url']->setOptions(NestedArray::mergeDeep($element['url']->getOptions(), $data->options));
}
$element['original_link'] = $link;
// Index using the link's unique ID.
$items[$link->getPluginId()] = $element;
}

… but unfortunately the description is not defined. You need to use the accessor method for now.

Leave a Reply

Your email address will not be published. Required fields are marked *