For Loop

Estimated reading: 2 minutes

And finally, because we’re working with WordPress, it’s very likely we will use loops often. By default the Timber Posts Module is set to use the Main Query, so use whatever WordPress is set to do for the current object query. Whenever you’re creating an archive layout, you will have access to the ‘posts‘ context variable. Here’s how a typical loop looks like:

{# loop over the context variable 'posts' #}
{% for item in posts %}
  <h3>{{ item.title }}</h3>
{% endfor %}

And just like that, you should see a bunch published post titles wrapped in h3 tags.

Mix Loop with Conditional

Sometimes you will want to show only a selection of the posts, for instance only the ones by a specific author. Instead of adding the {% if ... %}{% endif %} within the for-loop, you can add it immediately in the statement:

{# loop over the context variable 'posts', but only if that item is by author.ID equal to 2 #}
{% for item in posts if item.author.ID == 2 %}
  <h3>{{ item.title }}</h3>
{% endfor %}

Warning: this messes with the pagination

When doing this type of loop and conditional, keep in mind that the number of displayed results might (probably) not line up with the actual number of results in the posts variable. So if possible, always try to mix the conditional into the query arguments so that pagination is maintained.

Share this Doc

For Loop

Or copy link

CONTENTS