0

I've tried to theme a portion of a node by adding some values in to it using

  1. hook_theme and a twig template

I've used hook_node_view to add a few variables and then I have included the theme specified in hook_theme and printed it in twig template.

Here is the code; nothing is working like nothing.

function content_statistics_node_view(EntityInterface $node, EntityDisplay $display, $view_mode) {
    $node_count = some function called;
    foreach ($node_count as $key => $value) {
      $node_statistics = array(
        '#theme' => 'content_statistics_list',
        '#letter' => $value->letter,
        '#word' => $value->word,
        '#sentence' => $value->sentence,
      );
    }
  }
  $node->content['content_statistics_list'] = array(
    '#markup' => drupal_render($node_statistics)
  );
}

/**
 * Implements hook_theme().
 */ 
function content_statistics_theme($existing, $type, $theme, $path) {
   return array(
    'content_statistics_list' => array(
      'variables' => array('letter' => NULL, 'word' => NULL, 'sentence' => NULL),
      'template' =>  drupal_get_path('module', 'content_statistics') . '/templates/' . 'content-statistics-list',
    ),
  );
}

In content-statistics.html.twig, I have printed {{ letter }} but it is not showing anything on the node page. It is also causing an error.

Warning: Attempt to modify property of non-object in content_statistics_node_view()

2
  • The code you are showing doesn't even follow the correct PHP syntax. (See the brackets it is using, and count them.)
    – avpaderno
    Commented Feb 10, 2016 at 17:54
  • Btw. You should use \Drupal::service('renderer')->renderRoot() instead of deprecated drupal_render().
    – kenorb
    Commented Aug 5, 2017 at 11:02

1 Answer 1

2

Your hook_node_view() is incorrect, check the documentation and example implementations. The first argument is a $build array. That's the new $node->content: What your code is adding to $node->content should be added to $build.

Also, never render things yourself: Just put your render array ($node_statistics) in $build['content_statistics_list'].

It's also recommended to implement hook_entity_extra_field_info() and expose that key as an extra field. Then it can be shown/hidden based on the view mode.

0

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