Question

I'm trying to implement a list of events to a js calendar. So the data for the calendar are like this:

var studyEvents = {
    '04-03-2014' : '<span class="event">Event 1</span>',
    '05-08-2014' : '<span class="event">Event 2</span>',
    '12-09-2014' : '<span class="event">Event 3</span>'
};

In case the are more than one events on the same day, the data are like this:

var studyEvents = {
    '04-03-2014' : '<span class="event">Event 1</span>',
    '05-08-2014' : '<span class="event">Event 2-1</span><span class="event">Event 2-2</span>',
    '12-09-2014' : '<span class="event">Event 3</span>'
};

So what I'm doing is getting a list with all events ordered by date. I want to check if there are more than one events in on the same day. I'm thinking that I could check(since the list is ordered by date) if the event.date is not unique then there could be a way to put it on the same line.

var studyEvents = {
    {% for event in events %}
        '{{ event.date|date:"m-d-Y" }}' : '<span class="event">{{ event.title }}</span>'{% if not forloop.last %},{% endif %}
    {% endfor %}
};

I'm a bit lost with this one so any help would be much appreciated!

Was it helpful?

Solution

You can use the built-in templatetag regroup on date. https://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup

Example usage:

cities = [
    {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
    {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
    {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
    {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
    {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]

template:

{% regroup cities by country as country_list %}

<ul>
{% for country in country_list %}
    <li>{{ country.grouper }}
    <ul>
        {% for item in country.list %}
          <li>{{ item.name }}: {{ item.population }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top