3

Just wondering what the most efficient way to check whether a section has any entries or not. Based on this, I'm showing some content. The content doesn't take any information from the entries in the section, so it'll be a superfluous query no matter what.

For context, this is basically what it'll look like:

{% if craft.entries.section('whatever') | length > 0 %}
    <a href="www.com">Go here</a>
{% endif %}
4

Not a definitive answer at all, but you could at least add a .ids() on that so it only retrieves the entry ids and not all the entry data...

{% if craft.entries.section('whatever').ids() | length > 0 %}
<a href="www.com">Go here</a>
{% endif %}
  • Would this be better than doing .section().first.id? – peirix May 12 '17 at 8:23
  • .section().first.id will break if there is no ids. – Fred Carlsen May 16 '17 at 9:27
6

You can use {{ craft.entries.section('whatever').total() }} for that.

  • For some reason .total() is slower than .limit(1) | length, by ~10ms on average. And also this is only testing when there are 1 or 0 active entries. – peirix May 15 '17 at 13:17
  • That's a cool tip. Did you compare it to Jeremy's suggestion? – Fred Carlsen May 15 '17 at 13:20
  • Yeah, that was about the same as .limit(1) | length, so actually faster than total() – peirix May 16 '17 at 14:09

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.