Rendering the URL part of a link field in a Twig template should work equally for external, internal relative paths, and internal system paths

Created on 25 March 2022, over 2 years ago
Updated 2 September 2023, about 1 year ago

Problem/Motivation

Currently if you would like to have full control over your link text and link URL in a template, you are likely to find your way โ†’ to a monstrosity like this:

    {% if node.field_link.0.url.external %}
      <a href="{{ node.field_link.uri }}" class="button is-size-5">
        {{ node.field_link.title }}
      </a>
    {% elseif node.field_link.0.url.routeName %}
      <a href="{{ path(node.field_link.0.url.routeName, node.field_link.0.url.routeParameters) }}" class="button is-size-5">
        {{ node.field_link.title }}
      </a>
    {% endif %}

This is unintuitive and brittleโ€”

Proposed resolution

This much simpler code works:

{{ node.field_link.get(0).getUrl().toString() }}

but that is what {{ node.field_link.url }} should do in the first place!

Remaining tasks

User interface changes

None.

API changes

{{ node.field_link.url }} would be the same in most instances, but would appropriately render relative paths as /this-is-my-path instead of what it currently does, internal:this-is-my-path.

Data model changes

None.

Release notes snippet

๐Ÿ“Œ Task
Status

Active

Version

10.0 โœจ

Component
Themeย  โ†’

Last updated 1 day ago

Created by

๐Ÿ‡บ๐Ÿ‡ธUnited States mlncn Minneapolis, MN, USA

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom catch
  • ๐Ÿ‡บ๐Ÿ‡ธUnited States tea.time

    I ran into this too and while I know I could preprocess to extract the URL value for the template, I was curious if there was a simple Twig solution as well.

    This worked for me to print the URL appropriately for both internal and external links, with the link field formatter set to "Separate link text and URL":

    {% set url = content.field_url.0['#url'] ?? '' %}
    <a href="{{ url }}">This is my link</a>
    
Production build 0.71.5 2024