Extract Url & Title from link field in Drupal 8?

后端 未结 11 637
一生所求
一生所求 2021-01-31 05:29

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:<

相关标签:
11条回答
  • 2021-01-31 05:31

    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.

    0 讨论(0)
  • 2021-01-31 05:32

    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'] }}
    
    0 讨论(0)
  • 2021-01-31 05:32

    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.

    0 讨论(0)
  • 2021-01-31 05:33

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

    0 讨论(0)
  • 2021-01-31 05:35

    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,
    ];
    
    0 讨论(0)
  • 2021-01-31 05:42

    I just found the solution ...

    $partner->field_lien->uri // The url
    $partner->field_lien->title // The title
    

    My bad, hope it could help someone.

    0 讨论(0)
提交回复
热议问题