Get Link Attributes In Twig Of Menu In Drupal 8

January 31st, 2019  | Categories: Drupal, Drupal 8, Twig

PROBLEM
We’re using Pattern Lab with our Drupal 8 installation so I will need to get the link attributes of menu items so I can pass them to the link pattern. I am using the Link Attributes Widget for giving the option of opening links in new windows and adding classes to links.

However, I need to be able to get these attributes from the Drupal twig template to pass them into the Pattern Lab template.

I tried to do this months ago but couldn’t figure it out. Months later, I’m a lot better at twig than before. I went through looping through the items in item and getting the keys. Nothing was working. The only thing I could do was to output the link using the link function in Drupal. That would properly output the link.

But I wanted to use the link pattern in Pattern Lab!


SOLUTION
After a while at this, I stumbled upon a post on Drupal of someone trying to do the same thing (just get the attributes of a damn menu link in twig)!

Use this code to get the target and the classes. (This is looping through the items array… i.e. for item in items) Note that class is in an array so you might want to add |join(” “) afterward.

item.url.getOption("attributes").target
item.url.getOption("attributes").class

Now I can move forward!

Extra… But by the way, normally to get the target and classes of these for regular field links, use this:

field_link[0].options.attributes.target
field_link[0].options.attributes.class|join(" ")

No comments yet.

TOP