Drupal - How to add a variable to a twig field template?

Since you asked about passing the node title as a variable via the .theme file, you could use template_preprocess_field to do something like this:

  function themename_preprocess_field(&$variables, $hook) {
    if ($variables['element']['#field_name'] == 'field_example') {
      $variables['node_title'] = $variables['element']['#object']->getTitle();
    }
  }

then in your field--field-example.html.twig you could simply just use {{node_title}} to render the node title.

Also see 4k4's answer below.


There is a node object available in the variables of the field template, so you don't need a preprocess function.

To get the title from the node in a field template:

{{ element['#object'].label }}

Tags:

Theming

8