Extract Url & Title from link field in Drupal 8?

后端 未结 11 638
一生所求
一生所求 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:42

    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

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

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

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

    One more way is to add another field Path:Content if you are trying to fetch the URL in Views Fields

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

    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();
    
    0 讨论(0)
提交回复
热议问题