9

On a node page I would like to add the node title to the output alongside another another field (the example field).

I have created a new field--field-example.html.twig but am unable to access the node title variable as it is not available in the field template.

I need to add the variables into the theme preprocess: themename.theme.

How do I add the variable in themename.theme and what would be the corresponding entry in the field--field-example.html.twig ?

  • Use hook_preprocess_node to extract the value from the field that you would like to use in the template. – user21641 Feb 8 '16 at 11:13
  • @IvanJaros, I have updated the question now. – Taylor Taff Feb 9 '16 at 20:02
15

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.

  • I tried to edit your answer to include the one provided by 4k4 as it is correct but my edit was declined as it was deemed not relevant... – Taylor Taff Feb 15 '16 at 13:18
  • @TaylorTaff who approves edits? I never saw it. Will attempt to edit to include answer below. – Janey Feb 15 '16 at 13:27
  • @Janey many users with enough badges can review such edits. I have bookmarked your answers for future review. One more question: Are you guys sure that $variables['element']['#object']->getTitle(); is catchable in preprocess_field ? Because this would actually answer my question over here: drupal.stackexchange.com/questions/197497/… – nilsun Apr 10 '16 at 18:10
10
+50

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 }}
  • This answers the question but as the other answer by Janey will be more useful I added this to that answer and marked as accepted. – Taylor Taff Feb 15 '16 at 11:51
  • 1
    But your question was under the wrong assumption: " but am unable to access the node title variable as it is not available in the field template." – 4k4 Feb 15 '16 at 14:11
  • Yes 4k4, you are correct, my question was incorrect. – Taylor Taff Feb 17 '16 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.