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">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
<th>Priority</th>
</tr>
</thead>
<tbody id="taskTblBody">

</tbody>
</table>
</div>


Create the Template Block:
<script id="taskTemplate" type="text/x-jsrender">
<tr>
<td>{{:#data.get_id()}}</td>
<td>{{:#data.get_item('Title')}}</td>
<td>{{:#data.get_item('Status')}}</td>
<td>{{:#data.get_item('Priority')}}</td>
</tr>
</script>
Be sure to include all the files needed:


<script 
type="text/javascript"
src="/sites/Bwarfson/CScripts/jquery-1.7.1.min.js">
</script>
<script
type="text/javascript"
src="/sites/Bwarfson/CScripts/jsrender.js">
</script>


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
.get_web()
.get_lists()
.getByTitle('Tasks');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><RowLimit>500</RowLimit></View>");
this.collListItem = oList.getItems(camlQuery);
clientContext.load(
collListItem,
'Include(Id, Title, Status, Priority)'
);
clientContext.executeQueryAsync(
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>');
$('.message').append('<p>'+args.get_message()+'</p>');
$('.message').append('<p>'+args.get_stackTrace()+'</p>');
}));

}

The final result:

image

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.

    ReplyDelete