In Drupal 9, I need the ability to prepend Font Awesome icons to menu links.
I have attached Font Awesome 5 JS and CSS assets to my theme via *.libraries.yml
.
If I open a menu link in the DOM inspector and edit the markup of a link from this:
<ul class="clearfix nav">
<li class="nav-item">
<a href="#comments" class="nav-link nav-link-comments">Comments</a>
</li>
</ul>
to this:
<ul class="clearfix nav">
<li class="nav-item">
<i class="fas fa-comment"></i><a href="#comments" class="nav-link nav-link-comments">Comments</a>
</li>
</ul>
The Font Awesome JavaScript detects the empty <i class="fas fa-comment"></i>
element, and the result looks exactly like what I want it to look like.
However, it's been very tricky to add that markup to the link element programmatically.
I can do it with JavaScript DOM manipulation in a Drupal behavior, but I'd prefer to prepare the markup in Twig and preprocess.
After trying and rejecting a couple of other modules, I am now looking at menu_link_attributes
.
It's very easy to add the class .fa-comment
to this menu link:
<ul class="clearfix nav">
<li class="nav-item">
<a href="#comments" class="fa-comment nav-link nav-link-comments">Comments</a>
</li>
</ul>
I'm looking at an old forum thread which explains a template preprocess approach to matching classes starting with fa-
, and using that value to generate <i>
tags with the needed classes. This approach may have worked with Drupal 7.
The THEME_menu_link()
preprocess function does not seem to work in D8 and D9, so I am trying to rewrite it using THEME_preprocess_links()
. But when I drop a dump($variables)
; in this function, I do not see all the menu links.
While I'm looking for a different template preprocess function, I thought I'd describe the issue here, in case it's something you've encountered before.
NOTE: This question is technically a duplicate, but the old one never got answered so I think I'm safe to ask it again.