Drupal - How to get the valid URL of a Link field from within a Twig template?
Your PHP from your latest edit would translate into twig like this:
{{ node.field_my_link.0.url }}
This works like this, 0
returns the first item of the field item list, url
gets the url object and because twig will cast this object as a string this will call the magic method toString() and will output the url as a string value.
You only need to use url
, because twig looks automatically for the method getxyz()
if there is no property with that name xyz
.
You can access the render array element directly, in your case:
{{ node.field_my_link[0]['#url'] }}
You have to cover both cases: external and internal URLs.
First let's check if the URL is external and simply print its *.uri
.
Else if it's internal we have to wire its route name and parameters through Drupal's path($name, $parameters, $options)
function.
{% if node.field_link.0.url.external %}
<a href="{{ node.field_link.uri }}">
{{ node.field_link.title }}
</a>
{% else %}
<a href="{{ path(node.field_link.0.url.routeName, node.field_link.0.url.routeParameters) }}">
{{ node.field_link.title }}
</a>
{% endif %}