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.

markconroyThu, 10/03/2019 - 17:01

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.

  1. {% set parent = paragraph._referringItem.parent.parent.entity %}
    • Node Id: {{ parent.nid.value }}
  2. Node Title: {{ parent.title.value }}
  3. Link to node: {{ parent.nid.value }}">{{ parent.title.value }}
  4. 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.