Skip to main content

Drupal 8 - get node object from field template

Inside your theme, add this function to THEMENAME.theme file, for example /themes/scriptun/scriptun.theme:

function scriptun_preprocess_field(&$variables) {
    $node = $variables['element']['#object'];
    $variables['node'] = $variables['element']['#object'];
}

Where scriptun is of course your theme name. With this little snipped you have {{ node }} variable available in any field twig file:

<div{{ attributes }}>
    This field is rendered on node: {{ node.id }}
    <div{{ title_attributes.addClass(title_classes) }}>{{ label }}</div>
    {% for item in items %}
        <div{{ item.attributes }}>{{ item.content }}</div>
    {% endfor %}
</div>

 

More about theming:

Add new comment

CAPTCHA

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

We use cookies on our website to enhance your user experience. We also use Google analytics and ads.

Click here to read more I've read it