Printing Values of a Parent Node from a Drupal Paragraphs Field

Someone asked in Slack today how to print the URL of the node that a paragraph is on. I was up to the challenge.

First off, you can do this with php in your .theme file quite easily, but I like to keep my template items in my templates.

Here's the code I used to first get the node id, then the node title, and then create a link from these two pieces of information.

{% set parent = paragraph._referringItem.parent.parent.entity %}

 

What this does is:

 

  1. Set a variable called parent - note is uses parent twice and then entity

    You won't see parent or entity in your kint/dpm/dd output, which is a pity because entity is great - load the entity you want to get information from.

  2. Use parent to then get the node id value and title value parent.nid.value and parent.title.value.
  3. Create a link using this variables.

 

It's quite simple really. You can now use this approach to get other fields/data from your host node.

Filed Under:

  1. Drupal Planet
  2. Drupal
  3. Drupal 8
  4. Twig
  5. Frontend Development