Drupal 8 - Get a node url in twig

6.2k views Asked by At

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 ?

2

There are 2 answers

1
Anson W Han On BEST ANSWER

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.

0
George Potter On

I believe this should be the syntax?

{% for article_pair in node.field_articles_pairs %}
  {% for article in article_pair.entity.field_articles %}
    {{ path('entity.node.canonical', {'node': article.entity.id}) }}
  {% endfor %}
{% endfor %}

I think the first parameter in path is a string defining the type of path, not a value of the entity.