2

I'm confused about the new .one() argument in craft 3

If I want to grab all entries I write:

{% for entry in craft.entries.section('thing').all() %}
  {{ entry.title }}
{% endfor %}

Alls is nice and well. 20 something entries are returned.

But I want to fetch only the latest entry so instead of .all() I use .one() (which was formerly .first())

But when I write:

{% for entry in craft.entries.section('thing').one() %}
  {{ entry.title }}
{% endfor %}

It returns the error:

Impossible to access an attribute ("title") on a string variable ("3").

When I write:

{% for entry in craft.entries.section('portfolioEntry').limit(1).all() %}
  {{ entry.title }}
{% endfor %}

Then it works. But that's not the right way, is it?

3

.all() returns a collection of elements, which you can loop through with a for loop.

.one() returns a single element, so you cannot use a for loop to access it.

In this case you should just store the entry like:

{% set entry = craft.entries.section('thing').one() %} and then access {{ entry.title }} afterwards.

(Also keep in mind that entry is automatically populated for section URLs, so you may want to use another variable name)

| 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.