Tuesday, December 18, 2012

Using JsRender with the SharePoint JavaScript Object Model

Are you getting tired of writing a lot of JavaScript to manipulate the DOM while doing client side SharePoint development? This is simple tutorial about using templates with client side SharePoint development to avoid writing a lot of JavaScript to manipulate the DOM.  The template engine used in this tutorial is JsRender, which replaced jQuery templates.  Check out these links for more information on JsRender:

The following example was created in a content editor web part.

Create the HTML:
<div id="TasksTable">
<table id="taskTbl" cellpadding="5" cellspacing="5" border="1">
<tbody id="taskTblBody">


Create the Template Block:
<script id="taskTemplate" type="text/x-jsrender">
Be sure to include all the files needed:


And the JavaScript:
$(document).ready(function() {
if (typeof(_spBodyOnLoadWrapper) != 'undefined')
{_spBodyOnLoadWrapper();} //fix google chrome
ExecuteOrDelayUntilScriptLoaded(function ()
{ retrieveListItems() }, "sp.js");

function retrieveListItems() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext
var camlQuery = new SP.CamlQuery();
this.collListItem = oList.getItems(camlQuery);
'Include(Id, Title, Status, Priority)'
Function.createDelegate(this, function() {
//This is where the magic happens
$( "#taskTblBody" ).append(
$( "#taskTemplate" ).render( collListItem.get_data() )
}), Function.createDelegate(this, function(sender, args) {
$('.message').append('<p>Error loading tasks</p>');


The final result:


1 comment:

  1. Great post, thanks for putting this together.

    I just read about jsRender in Rob Windsor's Sharepoint 2013 CSOM course at PluralSight and I needed a clear example of a jsRender table to tinker with.