5

Craft 101: I have entries with many different fields, so I'm doing something like this:

{% set var = craft.entries.section('foo').slug('bar').first() %}

{% if var %}
  {{ var.field1 }}
  {{ var.field2 }}
  {{ var.field3 }}
  etc...
{% endif %}

Does Craft fetch the entry only once or every time the variable is called? I'm guessing only once but I'm not too sure, and some entries have 50+ fields.

4

The statement is only executed once.

You are essentially creating an elementCriteriaModel, returning the first element using the .first() parameter (which in this case is an Entry Model), and storing it in a variable; which you then can use to access your field values.

If you want to further increase performance you can wrap the whole block in a cache tag, which will speed up subsequent requests.

3
  • Thanks! I'm guessing this also applies if said variables are actually called further down in other "included" templates?
    – Paul
    Feb 1 '15 at 7:25
  • Yes and no — it applies anywhere that the variable is still in scope. Variables defined in a template do not automatically carry over to included templates. You would have to explicitly include the template using the with clause (i.e. {% include 'template.html' with {'var': var} %}). Feb 1 '15 at 8:58
  • Interesting consideration, I'll look into that. Thanks.
    – Paul
    Feb 1 '15 at 9:56

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.