Search code examples
drupaltwigdrupal-8drupal-nodes

Drupal 8 - Get a node url in twig


I have a content-type referring to an other content-type (a pair of articles), which refer to a content-type (an article).

I would like to redirect to the article url when the article block is clicked on my twig, so I came up with the code below

{% for i, value in node.field_articles_pairs %}

    <div class="related_article" onclick="onArticleClick({{ path('value.entity.field_articles[0]entity.node.canonical', {'node': node.id}) }})">

    </div>

    <div class="related_article" onclick="onArticleClick({{ path('value.entity.field_articles[0]entity.node.canonical', {'node': node.id}) }})">

    </div>

{% endfor %}

<script>
    function onArticleClick(link) {
        window.location.href = link;
    }
</script>

Unfortunately, this is not working, I've got an error saying that the route does not exists.

How can I refer to my article url with that complex structure ?


Solution

  • There's two different approaches you can use to get the node/entity reference url for output:

    • Option 1:

      1. Create a separate display mode (maybe name it "teaser") under the Structure > Content Types > [Parent Content Type] settings.
      2. Then create a node-type and display-mode-specific twig template (article--teaser.html.twig). In it, you can output the related_article div with click handler.
      3. Then in your existing parent node-type twig template, you can simply output {{field_articles_pairs}} as it will loop through and pull the custom twig template for each article entity referenced in the field.
    • Option 2:

    Add custom preprocess node functionality for the referencing/parent content type to include the urls with each field_articles value.