Skip to content

Instantly share code, notes, and snippets.

@ianshea
Last active August 29, 2015 14:04
Show Gist options
  • Save ianshea/0aed51a1f4845d055ff6 to your computer and use it in GitHub Desktop.
Save ianshea/0aed51a1f4845d055ff6 to your computer and use it in GitHub Desktop.
CraftCMS Range of Events
{#
I'm using this to build out a calendar. Not every month/day on the calendar has an event and I don't want a user to go into May 2034 and see nothing.
I needed a way to go from the current day and count out to the last event in the database and show everything in between. This is what I ended up doing.
This method assumes you have a channel of events.
Every event is assigned to an 'event' category with sub categories below it.
Every entry has an 'eventTime' date field within it.
I'm not worrying about recurring events. It's unneeded for this application.
#}
{# {% set category = craft.categories.slug('MySpecific Category') %} #}
{% set category = craft.categories.find() %} {# All Categories #}
{# Grab all the events related to the category and order them by the time they occur #}
{% set items = craft.entries.relatedTo( category ).order("eventTime").find() %}
{# Grab the last event in the list. #}
{% set lastItem = craft.entries.relatedTo( category ).order("eventTime").last() %}
{# This `slicer` is being used as a way to cut down on the looping twig needs to do #}
{% set slicer = 0 %}
<ul>
{# Here we start our loop on the current day and start at the number of the day. For instance. 7/15 = Day 195.
So you might have a range of 195 -> 303 assuming your last event in the database is 10/31 #}
{% for i in range( now|date('z'),lastItem.eventTime|date('z')) %}
{# Set an increment value which looks like +Xdays This is used to figure out the upcoming days. #}
{% set increment = "+" ~ (loop.index) ~ "days" %}
<li>{{ i }} - {{ date(now ~ increment)|date('m/d/Y') }}
{# Here we start another loop where we start looping through our event entries
this is where our slicer comes in. We start looping through items at index 0 to the end. #}
{% for item in items[slicer:] %}
{# Within here we run an if to check the date of the entry vs. the date of the looped day. #}
{% if date(item.eventTime)|date('z') == date(now ~ increment)|date('z') %}
{{ item.title }} - {{ loop.index }} {# Here is your output code #}
{# At the end we increment our slicer. If we're here. We've already displayed the events here in our
entries array so we can start our next loop from an index further in the entries array and cut down on loops
#}
{% set slicer = (loop.index - 1) %}
{% endif %}
{% endfor %}
</li>
{% endfor %}
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment