9

I'm trying to make a upcoming and past event page. I can make an if statement for displaying the past or upcoming events but the problem is if I limit the amount of entries to be displayed I realised it is still going through the other entries (obviously) so it wont display anything. So I was looking for any filter of some kind to only display entries based on field value greater then other value.

Something in the range of:

{% for entry in craft.entries.section('event').limit(2).search('eventDate < now') %}
<!-- Past events go here -->
{% endfor %}
11

You can combine a for and if statement in twig, so you don't necessarily need to use search.

Something like this might get you a bit closer:

{% for entry in craft.entries.section('event') if entry.postDate < now %}
{# output your event here #}
{% endfor %}

It'll just output what meets the criteria if your if statement. The bonus is it doesn't mess with your loop variables either, so things like loop.index work out as you'd expect (or at least they have for me so far).

EDIT: Here's an alternate way of doing it, which neatens up the query and adds ordering...

{% set events = craft.entries({
    section:  'event',
    startDate:  '< ' ~ now,
    order: 'postDate desc'
}).find() %}

{% for event in events %}
...
{% endfor %}
| improve this answer | |
  • 1
    Not messing with the loop.index is all I needed to tweak it a bit myself thanks! – Justin Dekkers Aug 1 '16 at 9:06
  • 5
    Does this still query the db for all entries within events? I'm sure the overhead is minimal but I've achieved the same using craft.entries.section('event').startDate( '< ' ~ now ) which would only retrieve entries that matched the criteria to then loop through. – Luke Pearce Aug 2 '16 at 15:58
  • @Luke - I guess it does, but I've not really experienced any performance issues doing it this way, so I've never needed to look into an alternative. If it was to become an issue in future, I'll check out your suggestion, thanks :) – Steve Holland Aug 3 '16 at 7:49
  • If you were going to add an ORDER BY statement to this, where would it go? – David Rhoden Sep 10 '18 at 16:06
  • 2
    @DavidRhoden I've updated the answer to give an example. – Steve Holland Sep 10 '18 at 16:34

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.