Skip to main content
  • Guides & Documentation

Knowledgebase

Featured articles, how-to guides and quick tips.

Get Node Values in Paragraph Templates - Twig - Drupal 8

Whilst developing in Paragraphs for Drupal 8, you may encounter a scenario where you need to get values from the Paragraph's node, and print them in the Paragraph template.

For example, if you wanted to retrieve the node URL, you would usually use the following in a node.html.twig template:

{{ url }}

Or, to retrieve the node's title value, you would use:

{{ node.label }}

But these values don't work in Paragraph templates! So for these, we'll have to use something slightly different.

In terms of twig syntaxes, here is a quick and easy list, which should be as easy as a simple copy and paste:

Getting the Node URL in a Paragraphs Twig Template:

Simply use the following syntax in your paragraph.html.twig files:

{{ url('<current>') }}

If you want to print the node title in a Paragraph template, it's a little more complicated.

First, you'll have to modify your theme_name.theme file. Obviously, you'll need to switch out theme_name for the name of your theme.

For instance, if you're using the Bartik theme, the file you'll be editing is bartik.theme.

Add the following code to your theme_name.theme file:

function theme_preprocess_paragraph(&$variables){
   $node = \Drupal::request()->attributes->get('node');
   $variables['nodetitle'] = $node->getTitle();
}

Be sure to replace the bolded text in the snippet above to the machine name of your theme. For example, in Bartik it would be:

function bartik_preprocess_paragraph(&$variables){
   $node = \Drupal::request()->attributes->get('node');
   $variables['nodetitle'] = $node->getTitle();
}

Note the bold text!

After we've done this, we're halfway there.

Now, open your paragraph.html.twig file, and where you wish to print the node's title, you can use:

{{ nodetitle }}

This will now print the title of the parent node in the Paragraph template, and you're all set to now add this to any paragraph.html.twig file in order to get the node title!

Happy theming!