I'm migrating a large custom module and theme from Drupal 6 and can't work out how to convert references to $node->body
and $node->teaser
since they are no longer fields in the node object, right?
3 Answers
Use this code in a preprocess hook:
$node = \Drupal::entityManager()->getStorage('node')->load($nid);
$view_builder = \Drupal::entityManager()->getViewBuilder('node');
$variables['node_full'] = $view_builder->view($node, 'full');
$variables['node_teaser'] = $view_builder->view($node, 'teaser');
$variables['body_full'] = $node->body->view('full');
$variables['body_teaser'] = $node->body->view('teaser');
And in twig
{{ node_full }}
{{ node_teaser }}
{{ body_full }}
{{ body_teaser }}
Use the rendered node and configure the view modes full, teaser or a custom view mode. The single rendered field does not work well with other code.
I've made some progress. It seems that
{{ node.body.value|raw }} ** unsafe! **
works well but I guess it skipping input filters, and
{{ node.body.value }}
shows the markup. Not quite sure how to get the body with input filters but not escape the markup.
Safety notice:
Don't use the raw filter if you cannot guarantee that the value is safe from unwanted user input!
-
1In a node template use {{ content.body }} and configure the field in the view mode.– 4uk4May 6, 2016 at 7:38
You can get the body in twig via:
{{ content }}
After adding this to your THEME.theme file:
function THEME_preprocess_node(&$variables) {
$node = &$variables['node'];
$node_array = $node->toArray();
$variables['node_teaser'] = $node_array['body'][0]['summary'];
}
You can pull it up in templates/node.html.twig with:
{{ node_teaser }}
{{ node.body }}
inside twig? I see some other modules do this, but from my theme I get"Object of type Drupal\Core\Field\FieldItemList cannot be printed.