I'm trying to create a menu that opens external links in a new tab but leaves internal ones alone.

I know i can use .setAttribute to add the target, but how do i determine if the link is external? Seems like i should be uering URL::$external, but not sure how.

It would be infinitely helpful if the API pages showed examples of use.

Comments

BeauTownsend’s picture

Try UrlHelper::isExternal
Documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Util...

\Drupal\Component\Utility\UrlHelper::isExternal('/node/5');  # FALSE
\Drupal\Component\Utility\UrlHelper::isExternal('http://www.drupal.org');  #TRUE
wheretoplaygames’s picture

{% if UrlHelper::isExternal(item.url) %}

Not sure why that doesn't work. Throws: Unexpected token "punctuation" of value ":"

BeauTownsend’s picture

I didn't realize you were asking about usage in a Twig template. UrlHelper::isExternal() is for use in your PHP code. Drupal's API pertains to the PHP portion of your themes & modules. For Twig documentation, see https://twig.sensiolabs.org/doc/2.x/.

To achieve specifically what you had in mind, I think the method used in the answer to this question on Stack Exchange should help: https://craftcms.stackexchange.com/questions/2544/whats-the-best-way-to-...

Hope it helps!

mmjvb’s picture

wheretoplaygames’s picture

Thanks for the link to twig, but not sure what i'm looking for there...

jwilson3’s picture

A few examples:

{# menu.html.twig #}
{% for item in items %}
external? {{ item.url.external }}<br>
{% endfor %}
{# node.html.twig #}
external? {{ node.field_link.0.url.external  }}