By: Omar Stewart
In this tutorial I’m going to quickly show you how you can leverage jQuery Templates to load up data retrieved from the Client Object Model and display it using a jQuery Template. There are tons of ways to template data in SharePoint. jQuery Templates are a clean way to display and format repetitive data via JavaScript. It’s an excellent way to output data retrieved from ajax calls.
In our example, we want a simple list of the events occurring today, pulled from a standard SharePoint Calendar. Let’s jump right in and write our script to grab Today’s Events from our SharePoint calendar.
Client Object Model Script
We’ll begin writing our script in Visual Studio, any editor will work.
The Script looks for the “Calendar” List, then fetches the items of interest using a CAML Query. We then specify which fields we’re interested in pulling from the result set. Once we’ve successfully retrieved our results, we build an object for each result and call the jQuery Template Function. “.tmpl()”
<script type="text/javascript">
var context = null,
web = null,
currentUser = null,
calendarList = null,
calenderEvents;
function getCurrentEvents() {
context = SP.ClientContext.get_current();
web = context.get_web();
//GET CALENDAR LIST
calendarList = web.get_lists().getByTitle('Calendar');
//GET TODAY'S DATE
var d = new Date();
var date = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
//CAML QUERY, GET ITEMS WITH TODAY'S DATE
var queryString = "<View Scope='RecursiveAll'><Query>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name='EventDate' />" +
"<Value Type='DateTime' IncludeTimeValue='FALSE' >" +
date +
"</Value>" +
"</Eq>" +
"</Where>" +
"</Query></View>";
var query = new SP.CamlQuery();
query.set_viewXml(queryString);
//GRAB CALENDAR EVENTS BASED ON QUERY
calendarEvents = calendarList.getItems(query);
//ONLY LOAD FIELDS OF INTEREST
context.load(calendarEvents, "Include(ID, Title, EventDate, Category)");
context.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
var listEnum = calendarEvents.getEnumerator();
while (listEnum.moveNext()) {
var event = listEnum.get_current();
//GET EVENT DATA
var title = event.get_item('Title');
var category = event.get_item('Category');
var image = getImageForCategory(category);
//BUILD EVENT DATA OBJECT
var eventData = { Title: title, Category: category, CategoryImage: image };
//RENDER EVENT USING TEMPLATE
$("#currentEventsTemplate").tmpl(eventData).appendTo("#CurrentEvents");
}
}
function onFail() {
alert("Request Failed.");
}
//GET CATEGORY IMAGE
function getImageForCategory(categoryName) {
var imageSource = "";
switch (categoryName) {
case "Birthday":
imageSource = "/_layouts/images/GigWerks/BirthdayCalendarEvent.png";
break;
case "Meeting":
imageSource = "/_layouts/images/GigWerks/MeetingCalendarEvent.png";
break;
default:
break;
}
return imageSource;
}
//EXECUTE FUNCTION WHEN SP.JS IS READY
ExecuteOrDelayUntilScriptLoaded(getCurrentEvents, "sp.js");
</script>
Building the template
Now that our script is pulling in all the events for the data and passing it to jQuery to handle rendering the template, we can begin building out template.
A jQuery Template is built in a <script> block, just as if it were a normal script. For the type, we must specify “text/x-jquery-tmpl”. Then we give our template an id, so we can tell jQuery which template we’re using for our data. For our template, we will be repeating list items, this will make for a simple template, shown below:
<script id="currentEventsTemplate" type="text/x-jquery-tmpl">
<li>
<img src="${CategoryImage}" /> ${Title}.
</li>
</script>
We can add the script block right underneath the Script Block we made in the first section.
Preparing the markup
In order for the template to be displayed on the page, we need to create a container for it. Since our template repeats list items, we’ll add an unordered list as our target container.
<div>
<ul id="CurrentEvents">
</ul>
</div>
References
All that’s left to do now is add our jQuery references, we’ll add these at the top of the text file we’ve been using. We need to add one for the jQuery library, and another for the templating engine.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
Putting it all together The HTML Form WebPart
For the purposes of our tutorial, we’ll be dropping all our script into a HTML Form WebPart. This may not be an ideal practice for your scenario, but it will do just fine for the purposes of this tutorial.
Browse to your SharePoint page, click to edit the page, then insert the HTML Form WebPart.

Then Click to edit the Form WebPart to view the Edit WebPart Pane.
Click to enter the Form’s Source Editor:

In the Form Source Editor, paste in ALL the Content we’ve created in the previous steps.

Save and click Okay to apply the form changes. The HTML Form WebPart will now render the items returned using the template we’ve designed:

The Complete Script to post into the HTML Form WebPart is:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script type="text/javascript">
var context = null,
web = null,
currentUser = null,
calendarList = null,
calenderEvents;
function getCurrentEvents() {
context = SP.ClientContext.get_current();
web = context.get_web();
//GET CALENDAR LIST
calendarList = web.get_lists().getByTitle('Calendar');
//GET TODAY'S DATE
var d = new Date();
var date = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
//CAML QUERY, GET ITEMS WITH TODAY'S DATE
var queryString = "<View Scope='RecursiveAll'><Query>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name='EventDate' />" +
"<Value Type='DateTime' IncludeTimeValue='FALSE' >" +
date +
"</Value>" +
"</Eq>" +
"</Where>" +
"</Query></View>";
var query = new SP.CamlQuery();
query.set_viewXml(queryString);
//GRAB CALENDAR EVENTS BASED ON QUERY
calendarEvents = calendarList.getItems(query);
//ONLY LOAD FIELDS OF INTEREST
context.load(calendarEvents, "Include(ID, Title, EventDate, Category)");
context.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
var listEnum = calendarEvents.getEnumerator();
while (listEnum.moveNext()) {
var event = listEnum.get_current();
//GET EVENT DATA
var title = event.get_item('Title');
var category = event.get_item('Category');
var image = getImageForCategory(category);
//BUILD EVENT DATA OBJECT
var eventData = { Title: title, Category: category, CategoryImage: image };
//RENDER EVENT USING TEMPLATE
$("#currentEventsTemplate").tmpl(eventData).appendTo("#CurrentEvents");
}
}
function onFail() {
alert("Request Failed.");
}
//GET CATEGORY IMAGE
function getImageForCategory(categoryName) {
var imageSource = "";
switch (categoryName) {
case "Birthday":
imageSource = "/_layouts/images/GigWerks/BirthdayCalendarEvent.png";
break;
case "Meeting":
imageSource = "/_layouts/images/GigWerks/MeetingCalendarEvent.png";
break;
default:
break;
}
return imageSource;
}
//EXECUTE FUNCTION WHEN SP.JS IS READY
ExecuteOrDelayUntilScriptLoaded(getCurrentEvents, "sp.js");
</script>
<script id="currentEventsTemplate" type="text/x-jquery-tmpl">
<li>
<img src="${CategoryImage}" /> ${Title}.
</li>
</script>
<div>
<ul id="CurrentEvents">
</ul>
</div>
I hope this has been a helpful introduction.
By: Omar Stewart