2

As I understand, I have (at least) the following two possibilities to list entries of a channel:

Possibility 1:

{% for entry in craft.entries.section('example').find() %}

Possibility 2:

{% set entries = craft.entries.section('example') %}
{% for entry in entries %}

Unfortunately, I am not experienced enough to understand the advantages and the disadvantates of these both possibilities (e.g. performance related etc.)

The only thing I see: in possibility 2 I can reuse "entries" within the same template.

I would be grateful for some further information on the differences.

Thank you very much! MISC

  • Although I can't comment on the performance of each, I can tell you that .find() is optional and can be removed under all circumstances. – darylknight Jul 13 '15 at 14:37
  • As described in Michael's answer, set vs find is a false choice. set stores a variable for later use, while find reduces an ElementCriteriaModel down to an actual array. They can be used separately, or together... there is no direct conflict between the terms. – Lindsey D Jul 13 '15 at 17:35
6

You're exactly right: The advantage of using the variable is that you can re-use it throughout your template, which helps keep things DRY.

When you use craft.entries in your template, Craft serves up an ElementCriteriaModel — This is an object that knows how to query the system for a set of entries... but it doesn't actually perform that query until you either (a) call the .find() method, or (b) use the object as an interable in a loop.

In other words, the first time you try to get an Array from the ElementCriteriaModel (either by creating the array explicitly with find() or by creating it implicitly by treating it as an Array — THAT'S when Craft does the work of perofmring the query.

Unless you need to do an operation directly on the array, you don't actually need to call the .find() method. It's perfectly acceptable to let Craft do the smart thing automatically:

{% set entries = craft.entries.section(...) %}
{% for entry in entries %}
   ...
{% endfor %}

There's often a slight advantage to doing it this way, because it means if that variable never gets used (perhaps it's hidden away in an unsatisfied conditional or something), Craft never does the work of performing the query.

| improve this answer | |

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.