ClientSideRendering basics

Lists in SharePoint 2013 are very minimal and nice looking. You can have multiple use cases for a list. For example a list of cars.

I made a very simple list of cars with three columns:
We can see the title the power and the manufacturer, but what is the unit of measurement for the power? To answer this question we should build in the unit.


To do so we need a simple JavaScript file called "CarListRendering.js":

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
(function () { 
 // create a CSR Context
    var csrContext = {}; 
    csrContext.Templates = {}; 
 // set a new template for the field horsepower
    csrContext.Templates.Fields = { 
        "Power": { "View": horsepowerFiledTemplate } 
    }; 
 
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(csrContext); 
})(); 
 
function horsepowerFiledTemplate(ctx) { 
 // return html that contains the value and adds the HP behind it and also color the text
 return "<span style='color :#0072c6'>" + ctx.CurrentItem[ctx.CurrentFieldSchema.Name]  + " HP</span>"; 
}

This script is calling a context that manages the rendering. The context should create a template for the power field. So when the field power will be rendered it calls its template and the template adds the unit "HP" (horsepower).

How to add the script and where?
You need to add the JavaScript to your view. So if you open your list you need to press "Edit Page", then click "Edit Web Part". In the new menu open the "Miscellanoeous" area and go the the field "JS Link".


In here you need to add the path to your file.

Note: Adding the JS Link will add the CSR just to this instance of the view. If you want the view to use the CSR in every instance you need to add the JS Link property in your solution in the schema.xml of the list (there you can define views and add things like JS Link).

Adding the path is simple, but you need to keep in mind that you have to add a prefix (or token). A prefix means that you need to add the location (the level like site collection or web) of the file. A prefix can be one of the following:
  • ~Site - the current SharePoint Site (web)
  • ~SiteCollection - the SiteCollection of the current web (Site)
  • ~Layouts - the layouts folder of your SharePoint version ("/_layouts/15" or "/_layouts/14")
  • ~SiteCollectionLayouts -  the layouts folder of the current SiteCollection ("/site/team/_layouts/15")
  • ~SiteLayouts - the layouts folder of the current Site ("/sites/team/subsite/_layouts/15")
So in my case it would be : ~Site/Style Library/CarListRendering.js

This was the last step. Now you can enter your view again and take a look at the result. Every body should know the unit of the power now.


Comments

Popular posts from this blog

How to support multiple languages in WPF