How to Use JSLink with List View Web Part in SharePoint 2013?
What is JSLink in SharePoint 2013?
JSLink is a new method of combining JavaScript, CSS, and HTML elements together to customize the look and feel of SharePoint Fields, List Items, List views, List forms, and web parts.
How to use JSLink in SharePoint 2013?
Here is the SharePoint 2013 JSLink example. Let’s customize the look and feel of static “% Complete” to a bar chart with the help of JSLink. At high-level, here are the steps:
- Create a JavaScript override file
- Upload the JavaScript file to the “Master Page Gallery >> Display Templates”, Set the content type and properties of the file.
- Set the JS Link property of the List view web part to point to the JavaScript file we’ve uploaded.
Step 1: Create your custom JS file to render the SharePoint list field
As the first step, We’ll have to create a new JS file that customizes the rendering of our field. Here is what I’ve created “TaskListDT.js”.
(function () {
var overrideCtx = {};
overrideCtx.Templates = {};
overrideCtx.Templates.Fields = {
'PercentComplete': { 'View': renderPercentComplete }
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();
function renderPercentComplete(ctx) {
var fieldVal = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
var percentComplete = fieldVal.toString().replace(" ", "");
var html = '';
html += "<div style='width:100%;height:20px;border:1px solid #AEAEAE;position:relative;'>";
html += "<div style='background-color:#0072C6;height:100%;width:" + percentComplete + ";'></div>";
html += "<p style='width:100%;text-align:center;position:absolute;top:0px;left:0px;margin:0px;'>";
html += percentComplete;
html += "</p>";
html += "</div>";
return html;
}
Step 2: Upload the JS file to Display Templates Folder
Navigate to Site Settings >> Click on “Master pages” link. >> Navigate to “Display Templates” folder >> Upload your custom JS file. (It could be uploaded anywhere on the site!)
While uploading, make sure you set the properties of the JS file. Set the content type as “JavaScript Display Template” and supply other required parameter values below.
Step 3: Set JS Link property of List View Web part in SharePoint 2013
The next step is to specify the location of your JavaScript file in the List view web part property. Be sure you follow the “~sitecollection/Your-JS-File-complete-Path” format! (Can also use: ~site, ~layouts, ~siteLayouts, ~siteCollectionLayouts tokens)
Here is the Typical “% Complete” column from SharePoint 2013 task list:
Here is our output – Bar charts for the “% Complete” column.
In earlier versions of SharePoint (SharePoint 2007, SharePoint 2010), we used to customize XSL for such requirements. Here is one among them: Building Bar chart to Display Progress in Task List
It worked like a charm! Thanks.
How to customize ListView Webpart in SharePoint Online?
Thank you for answering my questions! You’ve been a majestic SharePoint guru for many of us!