Extract Url & Title from link field in Drupal 8?

后端 未结 11 647
一生所求
一生所求 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: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,
    ];
    

提交回复
热议问题