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)
function is known as a theme hook and is an adaptation of theme_preprocess_node
. Within this function, we are passing by reference any variables accessible to the Node using &$variables
. Since everything in Drupal is...