Andy Holmes Andy Holmes - 7 months ago 21
Javascript Question

CLNDR.js & Underscore.js templating issue

I'm using the CLNDR.js plugin to create a nice mini calendar. I need to be able to access a value in an

event
function inside a
day
function. Let me try and explain below:

This is my JS code that populates the calendar. You'll see inside my JSON that I'm trying to add a
class: 'bank-holiday'
to the array of properties.

<script>
var clndr = {};

$( function() {

var currentMonth = moment().format('YYYY-MM');
var nextMonth = moment().add(1,'month').format('YYYY-MM');

var events = [
<?php
//Loop bank holiday dates from gov.uk website
$events = json_decode($englandAndWalesEvents);
foreach($events as $event){
echo "{ date: '".$event->date."', title: '".$event->title."', url: 'https://www.gov.uk/bank-holidays', class: 'bank-holiday' },";
}
?>
];

$('#mini-clndr').clndr({
template: $('#mini-clndr-template').html(),
weekOffset: 1,
events: events,
clickEvents: {
click: function(target) {
if(target.events.length) {
var daysContainer = $('#mini-clndr').find('.days-container');
daysContainer.toggleClass('show-events', true);
$('#mini-clndr').find('.x-button').click( function() {
daysContainer.toggleClass('show-events', false);
});
}
}
},
adjacentDaysChangeMonth: true,
forceSixRows: true
});
});
</script>


Below is my underscore.js template that populates my calendar:

<div class="days-container">
<div class="days">
<div class="headers">
<% _.each(daysOfTheWeek, function(day) { %><div class="day-header"><%= day %></div><% }); %>
</div>
<% _.each(days, function(day) { %><div class="<%= event.class %> <%= day.classes %>" id="<%= day.id %>"><%= day.day %></div><% }); %>
</div>
<div class="events">
<div class="headers">
<div class="x-button">x</div>
<div class="event-header">EVENTS</div>
</div>
<div class="events-list">
<% _.each(eventsThisMonth, function(event) { %>
<div class="event">
<a target="blank" href="<%= event.url %>"><%= moment(event.date).format('MMMM Do') %>: <%= event.title %></a>
</div>
<% }); %>
</div>
</div>
</div>


You can see in those code that I'm trying to utilise the
event.class
inside the
day
function. Is there a way to do this? You can see in the above code that the
event
function is being used to show
event.url
event.title
etc.

<% _.each(days, function(day) { %><div class="<%= event.class %> <%= day.classes %>" id="<%= day.id %>"><%= day.day %></div><% }); %>


Thanks in advance for any help with this,

Andy

Answer

It looks like you need to loop through the days variable, and then there is an events key. Using this you can access the classes.

<%
    var classes = '';
    if( day.events.length ){
        for( var i = 0; i < day.events.length; i++ ){
            classes += ' ' + day.events[i].class;
        }
    }
%>


<div class="<%= day.classes %><%= classes %>" id="<%= day.id %>"><%= day.day %></div>