Creating a theme file

The *.theme file is a PHP file that contains theme hooks for preprocessing variables. We will create a theme file specific to our theme that we can use to grab the comment count, based on each individual post, and then return the count to our Twig template as a variable that can be printed.

Let's begin by creating a new file called octo.theme and saving it to our themes/octo folder.

Next, we will add the following PHP code:

<?php

function octo_preprocess_node(&$variables) {
  $node = $variables ['elements']['#node'];
  $id = $node->id();

  // Create comment count variable for template
  $count = _octo_comment_count($id);
  $variables['comment_count'] = _octo_plural($count, 'Comment',
  'Comments');
}

The octo_preprocess_node(&$variables) ...

Get Drupal 8: Enterprise Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.