4

I've noticed code samples like the following that use the find() method.

{% for entry in craft.entries.section('blog').limit(5).find() %}
    <li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
{% endfor %}

I've noticed that this code sample works just as well without the find() method attached. Is there a particular reason we use find()? Are there instances where it's required? Should I be using it even if the code works without it?

1
  • Hi Tim - I asked the same thing a while ago - I think it was within Slack though. Someone else will give a much better answer I'm sure but...When working with entries the .find() is implied. Craft will do it automatically and it won't hurt anything if you call it. There are other times where find() is implied but I forget what that is. There are other cases though where you do need to call find().
    – Damon
    Apr 5 '16 at 1:18
6

The ElementCriteraModel description in the docs explains what the find() method does.

Essentially, when you use craft.entries you are building an ElementCriteriaModel object that represents the query that you want to make. That query doesn't actually happen until you call the find() method.

As the docs state, as soon as you treat craft.entries (or a variable that you have assigned it to) as an array, by using it in a {% for %} loop, or by calling the | length filter on it, find() is automatically called.

So in the example in your question, you can safely leave out the find() and it will be called automatically anyway when the {% for %} loop is executed.

1

There's also a really good answer explained in this ticket. Similar explanation but this made it click for me.

https://craftcms.stackexchange.com/a/23951/4433

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.