I\'m trying to retrieve the URL and the Title values of a Link field in Drupal 8.
In my custom controller, I retrieve the nodes with:<
This one works for me in twig:
content.field_link_name.0['#title'] // title
content.field_link_name.0['#url_title'] // url value
*you should use: "Separate link text and URL" widget in display
If you want to do this in a field template instead of a node template do this:
{% for item in items %}
{{ item.content['#url'] }}
{{ item.content['#title'] }}
{% endfor %}
Alternately, if this is not a multi-value field you can just do this instead:
{{ items|first.content['#url'] }}
{{ items|first.content['#title'] }}
You can render either the uri or text of a link field directly in the twig template. In the case of a node you can use either of the following within the twig template file (assumes the machine name of your link field is field_link
):
{{ node.field_link.uri }}
{{ node.field_link.title }}
One more way is to add another field Path:Content if you are trying to fetch the URL in Views Fields
Just to piggyback on the above, if you have an external link,
$node->field_name->uri
Will give you the URL, but if it's an internal you may need to tweak a bit more:
use Drupal\Core\Url;
$mylink = Url::fromUri($node->field_name[0]->uri);
$mylink->toString();