3

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?

  • 1
    You probably do not need any custom code to do this. Use a Display Mode (a concept from Drupal 7) to set how to display the body (i.e. trimmed = teaser), and then print out the content in twig. If you need to print the body manually, then you can do that as well in twig. See api.drupal.org/api/drupal/… and drupal.org/node/1918824 – mradcliffe Apr 11 '16 at 14:31
  • So I can't use just {{ 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. – Nic May 5 '16 at 20:14
8

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.

0

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!

  • 1
    In a node template use {{ content.body }} and configure the field in the view mode. – 4k4 May 6 '16 at 7:38
0

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 }}

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.