0

I am using paragraphs to render a number of nodes on a page. The nodes are obtained through an entity reference field called 'field_nodeslist' in my cards paragraph type. The cards are then rendered using a custom view layout.

Here is a snippet of my view layout:

<a href="????">
   <h3>{{ content.top_region|striptags}}</h3>
   <p>{{ content.middle_region }}</p>
</a>

The problem I am having is printing the relative path for each referenced node. I have tried the following twig commands but have not had any success so far:

<a href="{{ url }}">
<a href="{{ uri }}">
<a href="{{ node.id }}">
<a href="{{ link }}">
<a href"{{ content.field.0['#url'] }}">

The following allows me to manually specify the node id in twig however that's not what I am looking for:

<a href="{{ path('entity.node.canonical', {'node': 6 }) }}">

Any ideas?

Notes/Thoughts: In my first code snippet, the fields in 'top_region' just contains the nodes title. There was an option to link the field to content however I had to add the '|striptag' filter in twig due to additional markup messing up the style. Is it possible to grab the url path from the node title?

0

You probably need to work more in UI to configure what is in {{ content }} and then render the fields as they are.

If still necessary you can use {{ node }} respectively {{ paragraph }} to access all field values, see How to retrieve value of hidden field in twig?, but you can't access the url directly. You have to build this with the help of the raw database value target id, see How to print the URL path of a referenced node using paragraphs?.

BTW the result is the same as the entity method toUrl() would provide, only that this method is blocked by the twig sandbox policies. As a third (least favourable) option you can change this, too, see https://stackoverflow.com/questions/40091324/allow-new-methods-in-sandbox-policy-in-twig-drupal-8

  • Thanks 4k4. Do you know how I can obtain the raw database value of target id? – Dean May 23 at 7:22
  • node.field_example.target_id or paragraph.field_example.target_id, see your last question I've linked. – 4k4 May 23 at 7:26
  • Thanks 4k4. I'm still having difficulty following despite reading over the material. Is target_id suppose to be the value of a particular node/paragraph id or am I off track? – Dean May 23 at 7:31
  • target_id is the nid of the referenced node you are trying to print the relative url for. – 4k4 May 23 at 7:42
  • Thanks 4k4. I thought that was the case. Is there a twig function where drupal automatically fetches the url for each node rendered that I can insert in my view layout twig template? I would prefer not to hard code the relative path in my twig template for every node if possible. – Dean May 23 at 7:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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