1

I have a content type with a field « referenced entity » called field_suggestion_articles.

User can choose related content and a view displays this list of related content at the bottom of the content. The views uses "content" (display mode, a template like teaser) and not fields.

enter image description here

I use a loop to display this list in node--article--related-content.html.twig:

{% for key,value in node.field_suggestion_articles.value %}
    {# display the title #}
    {{ content.field_suggestion_articles[key] }}

    {# display a text field #}
    {{node.field_suggestion_articles[key].entity.field_resume_suggestion_article.value|raw}}

{% endfor %}

But I don’t know how to get the node urls of these related content.

When I dump node.field_suggestion_articles.value, I get the target_id of the node so I guess I should use it to retrieve the url. But I’ve tried a lot of solutions found on Drupal forums and here on stackExchange but without success.

Could you point me in the right direction ?

14
  • something like this? drupal.stackexchange.com/questions/202609/… so in your case {{ path('entity.node.canonical', {'node': node.field_suggestion_articles[key].entity.id}) }} should work i think
    – Leigh
    Commented Jan 8, 2020 at 10:59
  • @Leigh It works ! I've already seen this answer butI didn't adapt it correctly. Could you post an answer ? I will accept it. Commented Jan 8, 2020 at 11:03
  • Rendering raw field values is unsafe. I would take a different approach. When you render the referenced entity in a view mode like teaser you get a second twig template specific to the referenced content type and this view mode, where you can render the fields of the children entity and also the url like Drupal does this for teasers out-of-the-box.
    – 4uk4
    Commented Jan 8, 2020 at 11:03
  • @4k4 Not sure to understand. You mean, I can use the native "link field" available in the view mode ? Commented Jan 8, 2020 at 11:07
  • Not a field, in a node template the url is provided in a variable {{ url }}.
    – 4uk4
    Commented Jan 8, 2020 at 11:09

1 Answer 1

2

What they've done on this post should do the trick How do I get the node URL in a Twig template?

So in your case this should work:

{{ path('entity.node.canonical', {'node': node.field_suggestion_articles[key].entity.id}) }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.