2

Let's say I'm outputting a list/nav of categories, with the count of entries in each category, as described in other questions:

{% nav category in craft.categories.group('...') %}
   {% set entryCount = craft.entries.relatedTo(category).total() %}
   {{ category.title}} ({{ entryCount }})
{% endnav %}

On a site with plenty of categories (more than 100 in this case), that seems like a lot of relatedTo queries. Is there a way I could accomplish the same thing with fewer queries / better performance?

2

I don't think you'll be able to avoid the database queries, but you'll definitely want to use cacheing here, and set a high cache time if possible.

Wrap your code in {% cache %} tags like below:

{% cache globally for 1 month %}
{% nav category in craft.categories.group('...') %}
   {% set entryCount = craft.entries.relatedTo(category).total() %}
   {{ category.title}} ({{ entryCount }})
{% endnav %}
{% endcache %}

If this navigation appears on every page, use the "globally" tag.

2

Another option would be to use the rarely talked about template hook feature in Craft. The link shows some examples of how to use it and the control panel uses it in one or two places to speed things up.

But from the PHP side, you'd be able to grab all of the data you'd need from the database (using commandBuilder(), joins, etc.), then return it all to the template formatted in a way it can easily consume.

  • Thanks for the answer Brad. Is there an advantage to using a template hook vs a plugin variable to achieve this? Other than with the template hook you get access to the context? – Peter Tell Feb 10 '15 at 21:16
  • Access to the context is the main difference, I think. – Brad Bell Feb 10 '15 at 21:20

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.