How do we theme node view component? I've tried to theme a portion of a node by adding some values in to it using


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 =&gt; $value) {
      $node_statistics = array(
        '#theme' =&gt; 'content_statistics_list',
        '#letter' =&gt; $value-&gt;letter,
        '#word' =&gt; $value-&gt;word,
        '#sentence' =&gt; $value-&gt;sentence,
      );
    }
  }
  $node-&gt;content['content_statistics_list'] = array(
    '#markup' =&gt; drupal_render($node_statistics)
  );
}

/**
 * Implements hook_theme().
 */ 
function content_statistics_theme($existing, $type, $theme, $path) {
   return array(
    'content_statistics_list' =&gt; array(
      'variables' =&gt; array('letter' =&gt; NULL, 'word' =&gt; NULL, 'sentence' =&gt; NULL),
      'template' =&gt;  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()
Your hook_node_view() is incorrect, check the documentation and example implementations. The first argument is a $build array. That's the new $node-&gt;content: What your code is adding to $node-&gt;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.