Extract Url & Title from link field in Drupal 8?

2019-03-09 11:12发布

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:

$storage = \Drupal::entityManager()->getStorage('node');
$nids = $storage->getQuery()
    ->condition('type', 'partners')
    ->condition('status', 1)
    ->execute();

$partners = $storage->loadMultiple($nids);

When I loop throught all my nodes, to preprocess vars I'll give to my view, I would like to retrieve the URL and the Title.

foreach ($partners as $key => $partner) {
    $variables['partners'][] = array(
        'image' => $partner->field_logo->entity->url(),
        'url'   => $partner->field_link->value, // Can't retrieve values of link field
    );
}

Unfortunately, I don't found how to retrieve the URL and the Title of field_link.

Thanks for your help.

9条回答
劫难
2楼-- · 2019-03-09 11:46

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.

查看更多
神经病院院长
3楼-- · 2019-03-09 11:51

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

查看更多
Root(大扎)
4楼-- · 2019-03-09 11:52

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();
查看更多
聊天终结者
5楼-- · 2019-03-09 11:53

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 }} 
查看更多
唯我独甜
6楼-- · 2019-03-09 11:56

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'] }}

查看更多
做自己的国王
7楼-- · 2019-03-09 11:57

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.

查看更多
登录 后发表回答