Skip to main content

Forcing all menu links to use absolute links in Drupal 8

In a recent project, we were using an external service that pulls our site into their system and injects their content into our project. The issue we ran into was that the third party was overwriting all links in the template we provided with their HTTP host, causing the menu system from our Drupal site to break. To get around this we needed to generate absolute links for all of our menus.

In order to accomplish this we used template_preprocess() to dynamically provide our site's hostname as a variable:

  1. /**
  2.  * Implements template_preprocess().
  3.  */
  4. function MYTHEME_preprocess(&$vars, $hook) {
  5.   if ($hook == 'menu') {
  6.     $vars['host'] = \Drupal::request()->getHost();
  7.   }
  8. }

Then, we copied the menu.html.twig file into our theme and made the following adjustments:

  1. {#
  2.  
  3. #}
  4. {% import _self as menus %}
  5. {#
  6.   We call a macro which calls itself to render the full tree.
  7. #}
  8. {{ menus.menu_links(items, attributes, 0, host) }}
  9. {{ kint(host) }}
  10.  
  11. {% macro menu_links(items, attributes, menu_level, host) %}
  12.   {% import _self as menus %}
  13.   {% if items %}
  14.     <ul{{ attributes.addClass('uk-list', 'uk-link-text') }}>
  15.       {% for item in items %}
  16.         <li{{ item.attributes }}>
  17.           {% if not item.url.isExternal() %}
  18.             {% set item_path = item.url|render %}
  19.             <a href="{{ host }}{{ item_path }}">{{ item.title }}</a>
  20.           {% else %}
  21.             {{ link(item.title, item.url) }}
  22.           {% endif %}
  23.           {% if item.below %}
  24.             {{ menus.menu_links(item.below, attributes, menu_level + 1, host) }}
  25.           {% endif %}
  26.         </li>
  27.       {% endfor %}
  28.     </ul>
  29.   {% endif %}
  30. {% endmacro %}

Here, we passed the 'host' variable provided by template_preprocess() into the 'menu_links' macro.

Within the macro, we check whether the item.url is external. If it is, we print it as normal because it will already be absolute.

If it is not external, we render the internal url into a variable, and manually create our link with our hostname variable from the attributes array.

Props to Andy Blum for working through much of this fix.

One potential issue:

Attributes that are normally passed through the link() function might be left off the manually created anchor.


Comments