Published: Thu 03 Oct 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 %}


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.



Please don't forget that twig is also PHP and it can benefit from using OOP, because paragraph variable is an object you can use all the methods that are available for it in ParagraphInterface. So to get the node parent entity you need just call method getParentEntity() and that is it. Example: {% set parent = paragraph.getParentEntity() %}


Have you considered caching scenarios? This twig template output now has a dependency on another entity, not just the paragraph. When that entity title changes, will the cached template output be regenerated?

In reply to by John Pitcairn (not verified)


That's a good question, and I'm not sure what the answer is. I'd have to check.

This is not something I've ever done on a live site, it was just an answer to someone on Slack that I turned into a blogpost.

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.