2

I'm new to Drupal 8 and Twig and I can't figure out what the equivlent of field_view_field is? So lets say I did this in Drupal 7 within a template file:

print render(field_view_field('node', $node, 'body', array(
    'type' => 'text_summary_or_trimmed',
    'label' => 'hidden',
)));

How would I output a custom field in drupal 8 template?

4

The php equivalent in drupal 8 is:

$build = $node->body->view('view_mode');
$output = \Drupal::service('renderer')->renderRoot($build);

In twig you don't need to render yourself, twig does this for you. So you can simply put the first line in a preprocess function:

function theme_preprocess_hook(&$variables) {
   $variables['body123'] = $node->body->view('view_mode');
}

and output in twig:

{{ body123 }}

Edit: I see you are using a field formatter, not a view mode, and use the preloaded node, so this is the preprocess for a node template:

function mytheme_preprocess_node(&$variables) {
       $variables['body123'] = $variables['node']->body->view(array('type' => 'text_summary_or_trimmed'));
}

Put this in the mytheme.theme file in the theme root directory.

More information is available in the change record.

  • Hi, thanks for the rpely, I'm getting a 'Fatal error: Call to a member function view() on null' however when I try to use it from my theme file – karl Nov 11 '15 at 14:13
  • Got rid of that error I was putting it in bartiksub_preprocess_page but now not getting anything back – karl Nov 11 '15 at 14:24
  • There's a small bug in the preprocess code (magic $node var). If it's like D7 you should find that in $variables['node'] – Clive Nov 11 '15 at 14:32
  • You have the load $node first. If you use the node that is preloaded, then you can use $variables['node'] in preprocess. – 4k4 Nov 11 '15 at 14:32
  • Hi, thanks, I'm not totally following, so you mean I need to do: theme_preprocess_hook($node, &$variables) ? – karl Nov 11 '15 at 14:58

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.