3

How can I get the total rows number in views-view-fields.html.twig template file in Drupal 8? In Drupal 7, I can get it by the following code.

$view = views_get_current_view();
$view->total_rows;

Is there any variable to render the total number of rows in Drupal 8?

  • {{ view.total_rows }} is working when pager NOT set as Display a specified number of items, set as mini or full will print the total row number. – wzh Dec 20 '16 at 6:45
  • For some reason, it seems to work only on FULL, at least on a 8.4.x site. Not on mini – Mescalito Nov 21 '17 at 15:19
  • You should do these things in preprocess functions. Look here for a working snippet on views count: stefvanlooveren.me/blog/get-views-row-count-twig-drupal-8 – Stef Van Looveren Jun 27 '19 at 14:43
3

You can use simple code {{ view.total_rows }} in every file template views. Variable view is global.

  • I think {{ view }} variable is not available in views-view.html.twig. – Ashish Deynap Dec 20 '16 at 4:37
  • Thanks for reply {{ view.total_rows }} print only 0 as value in both views-view-fields.html.twig & views-view.html.twig when there suppose 5 in my case. – wzh Dec 20 '16 at 4:40
  • @AshishDeynap you can debug with {{ dump(_context|keys) }} – MrD Dec 20 '16 at 4:42
  • @wzh what's your field type? – MrD Dec 20 '16 at 4:43
  • 2
    Oddly enough, {{ view.total_rows }} is working when pager NOT set as Display a specified number of items, set as mini or full will print the total row number, thanks! – wzh Dec 20 '16 at 6:42
4

In Drupal 8, views-view.html.twig contains few pre defined variables. Among them, there is a {{ rows }} variable that contains "The results of the view query, if any."

To get total number of row count, use {{ rows | length }}. It will print total number of rows count and if you want it in a variable, do as {% set count = rows | length %}

  • Thank you for quick reply but I think {{ rows }} only available views-view.html.twig level not at views-view-fields.html.twig that is where I want it to show. – wzh Dec 20 '16 at 4:30
  • Not used it actually, but found a variable in views-view-fields.html.twig row: The raw result from the query, with all data it fetched. – Ashish Deynap Dec 20 '16 at 4:34
  • Yes it is row not rows so {{ rows | length }} doesn't work – wzh Dec 20 '16 at 4:41
  • you can use drupal.org/project/views_record_count module – Shreya Shetty Dec 20 '16 at 5:25
  • 1
    This is (no longer?) correct for views-view.html.twig, because rows always is an array containing only one nested array. However {% set count = rows.0['#rows'] | length %} worked for me in v8.4.3 – Hudri Jan 3 '18 at 13:26
1

you can use {{ view.result | length }} in views-view-fields.html.twig

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.