I'm new to Drupal. I've just started a custom theme in Drupal 8 and created a new field under Content Type. This field value is a custom class for each page. From the documentation I should be able to display the field contents of "field_body_class" with the following, neither of which display.



I've checked to make sure the field was not hidden, which it was not.


You are probably a bit confused.

Variables are only available in specific templates. So the value of a field which is attached to an entity (like a content type) is only available in the template for that entity.

To make the body class field value available in a different template you need to

  • make a preprocess function for the template.
  • fetch the entity that has the field
  • expose it to the template.

For you it could look something like this.

function theme_name_preprocess_page(&$variables) {
   // Define {{ body_class }}  in the template.
  if (!empty($variables['node']) && !empty($variables['node']->field_body_class)) {
    $variables['body_class'] = $variables['node']->field_body_class->value;
  • That helps a bunch, but I am certainly confused. I was using it in the specific page template. page--node--2.html.twig Shouldn't it be available? – Klav Oct 17 '16 at 16:28
  • @Klav No this is expected behavior – googletorp Oct 17 '16 at 16:51
  • 1
    @NoSssweat You don't get it - he wants to add the value from the body class field to the actual body class, which lives in the page template. So he can't use the node template for anything – googletorp Oct 18 '16 at 8:32
  • @googletorp thx, I get it now, this is nifty. – No Sssweat Oct 18 '16 at 8:34

The page.html.twig template doesn't get any content variable. It gets a page.content variable, but that is the rendered content of the content region, which means you won't get page.content.field_body_class.

To get the field value, you need to implement a preprocess function for the node template and set a new variable initialized to the field value.

function mytheme_preprocess_node(&$variables) {
  if (!empty($variables['node']->field_body_class)) {
    $variables['body_class'] = $variables['node']->get('field_body_class')->value;

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.