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 %}

2 Answers 2

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 %}
7
  • 1
    Not messing with the loop.index is all I needed to tweak it a bit myself thanks! Aug 1, 2016 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. Aug 2, 2016 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 :) Aug 3, 2016 at 7:49
  • If you were going to add an ORDER BY statement to this, where would it go? Sep 10, 2018 at 16:06
  • 2
    @DavidRhoden I've updated the answer to give an example. Sep 10, 2018 at 16:34
3

Craft has changed since the above answer was given. The now object must be a part of the string, rather than concatenated as an object.

so instead of:

{% set futureEntries = craft.entries.section('events').dateAndTime('>= ' ~ now) %}

use:

{% set futureEntries = craft.entries.section('events').dateAndTime('>= now') %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.