Published: October 3, 2019
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 %}
- Node Id: {{ parent.nid.value }}
- Node Title: {{ parent.title.value }}
- Link to node: {{ parent.title.value }}
What this does is:
-
Set a variable called parent - note is uses
parent
twice and thenentity
You won't see
parent
orentity
in your kint/dpm/dd output, which is a pity becauseentity
is great - load the entity you want to get information from. - Use
parent
to then get the node id value and title valueparent.nid.value
andparent.title.value
. - 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.