Saturday, September 19, 2015

SharePoint 2013 CSR

Introduction

In SharePoint 2013 the Client Side Rendering (CSR) is nothing more than a JavaScript framework used to customize the interface of the List and forms. CSR is used to render the display templates at client side using JavaScript. Prior versions of SharePoint used to handle the display templates at Server side using XSLT in 2010 and CAML in 2007.
SharePoint 2013 itself uses CSR framework in many places like Search Results, Lists and Document Libraries. Therefore CSR is the best way to modify the user Experience (UX).

How it works

Unlike Previous versions where the rendering was handled at Server side using the XSLT or CAML, In SharePoint 2013 the only step performed by the Server side webparts is to dump the raw data in JSON format in the page. And when the Page Loads the CSR framework actually forms the HTML with help of CSR templates and the raw data.
Therefore the HTML is the result of the combination of CSR templates and raw data,
HTML => CSR + Raw data

Customizing with CSR

To use this framework we need to define and override the template. The template is nothing but the JavaScript object containing various options for rendering the template. 

Following is the basic structure of the template.
(function () {
    var ctx = {};
    ctx.Templates = {};
    ctx.Templates.Header = undefined;
    ctx.Templates.Footer = undefined;
    ctx.Templates.Item = undefined;
    ctx.Templates.OnPreRender = undefined;
    ctx.Templates.OnPostRender = undefined;
    ctx.Templates.Fields = {};
    ctx.ListTemplateType = undefined;
    ctx.BaseViewID = undefined;

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();

The line "SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx)" , actually inserts our custom template on the SharePoint 2013 rendering stack. Note that the call to this function must be inserted in self-invoking JavaScript function so that it gets called on the page load and parameter to this function are the various override options .

Example

Let’s have a look at a simple example where we have a list called car details which contains 3 columns Title, Price and Color. In this example we will override the field color in list view where the text in the color column will be actually rendered in the color entered by the user.


1. Create JS Override template file as shown in the following figure



2. Upload the file to Master page library





3. While uploading select content type as “JavaScript Display Template”, Target Control type as “View”, Standalone as “Override”, Target Scope as “/”.







4. Edit the List view webpart and enter the JavaScript file path created in step 1 under JSLink Property.

The Full path is “~site/_Catalogs/masterpage/CSRCarDetails.js”.

5. Output

a. Before Applying Custom CSR Template

b. After Applying Custom CSR Template

No comments:

Post a Comment