I'm trying to display the number of total search results on my search results page, using the core search module. I've tried manipulating item-list.html.twig and item-list--search-results.html.twig by displaying items|count but when there are more than ten results, items|count only captures the number of results on that page.

I'm considering installing Search API and working with views, but that seems like overkill for this one little modification.

  • You will need to fetch the total results count from the pager variables. Best place to doing so is a custom implementation of the SearchController. I may provide a short example when I'm back in my office and nobody gave another answer yet. – Mario Steinitz Jan 24 '18 at 2:38
  • Added a less invasive example including theme preprocess hooks. – Mario Steinitz Jan 24 '18 at 5:15

The search queries of Drupal 8 use the global pager. The total results count is available within its global $pager_total_items variable.

So the easiest way of showing the amount of total items is using this variable within a hook_preprocess_HOOK() of your template in your *.theme file.

For example, if you'd like to use the total results count within the item-list--search-results.html.twig, HOOK needs to be replaced by its theme hook item_list__search_results:

 * Implements hook_preprocess_HOOK() for item_list__search_results.
function mytheme_preprocess_item_list__search_results(array &$variables) {
  // The $pager_total_items variable is a global
  // array keyed by the pager element increments.
  global $pager_total_items;

  // Assuming you have one paged list on your page only,
  // the element's key should be 0.
  $variables['total_items_count'] = isset($pager_total_items[0]) ? $pager_total_items[0] : 0;

Then you can access this variable like {{ total_items_count }} within the template.

  • 1
    This was perfect! The only thing missing is &$variables in the function arguments. With that addition, works like a charm. Thank you! – JOakland Jan 25 '18 at 0:26
  • You're right. Added it accordingly. – Mario Steinitz Jan 25 '18 at 0:40

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.