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:<
At the node level, inside your Twig template you can use:
{{ content.field_link.0['#url'] }}
& {{ content.field_link.0['#title'] }}
For example:
<a href="{{ content.field_link.0['#url'] }}">{{ content.field_link.0['#title'] }}</a>
field_link
being the name of the link field in question.
Updated for Drupal 8
To get the url all you need to do is:
{{ content.field_link_name[0]['#url'] }}
To get the link text:
{{ content.field_link_name[0]['#title'] }}
After rendering a block if you want to access the link field used in it then you can use like this $render['field_target_url']['#items']->uri inside node preprocess hook.
I am doing this link separation for ECK fields and this solution really helped me. I have updated the code for ECK fields for apply inline style in twig file like this:
<a style="color: {{ entity.field_link_color[0] }};" href="{{ entity.field_link[0]['#url'] }}"> {{ entity.field_link[0]['#title'] }} </a>
To get url:
{{ entity.field_link[0]['#url'] }}
To get link title:
{{ entity.field_link[0]['#title'] }}
If you're doing it in a preprocess, I'd suggest to base your code on LinkSeparateFormatter.php. It shows the idea on how to get the title from the link field. Here's a way to do it.
use Drupal\Component\Utility\Unicode;
//...
$field_link = $entity->field_link->first();
$link_url = $field_link->getUrl();
$link_data = $field_link->toArray();
// If you want to truncate the url
$link_title = Unicode::truncate($link_url->toString(), 40, FALSE, TRUE);
if(!empty($link_data['title'])){
// You could truncate here as well
$link_title = $link_data['title'];
}
$variables['content'] = [
'#type' => 'link',
'#url' => $link_url,
'#title' => $link_title,
];
I just found the solution ...
$partner->field_lien->uri // The url
$partner->field_lien->title // The title
My bad, hope it could help someone.