SP 2013: Using the JSLink property to change the way your field or views are rendered in SharePoint 2013

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

Recently I’ve had the pleasure (and adventure..) of upgrading a few SharePoint 2010 solutions to SharePoint 2013. One of the things that come up in literally every project I’m involved in, is the ability to quickly and easily change how a list is rendered. More specifically how the fields in that list should be displayed.

Luckily in SharePoint 2013, Microsoft have extended the SPField with a new proprety called JSLink which is a JavaScript Link property. There’s a JSLink property on the SPField class as well as a "JS Link" property on for example List View Web Parts. If we specify this property and point to a custom JavaScript file we can have SharePoint render our fields in a certain way. We can also tell for example our List View Web Parts to point to a specific JavaScript file, so they’re also extended with the JS Link property.

In this blog post I’ll briefly explain what the "JS Link" for a List View Web Part can look like and how you can set the property using PowerShell, C# and in the UI. I’ll also mention ways to set the SPField JSLink property, should you want to use that.

Final results

If you follow along with this article you should be able to render a similar result to this view in a normal Task List in SharePoint 2013:

image

You can see that the only modification I’ve made right now is to display an icon displaying the importance of the task. Red icons for High Priority and Blue and Yellow for Low and Medium.

Since it’s all based on JavaScript and we’re fully in control of the rendering, we could also change the rendering to look something like this, should we want to:

image

As you’ve may have noticed I haven’t put down a lot of effort on styling these elemenbts – but you could easily put some nicer styling on these elements through the JavaScript either by hooking up a CSS file or by using inline/embedded styles.

Configuring the JSLink properties

Okay all of what just happened sounds cool and all. But where do I actually configure this property?

Set the JS Link property on a List View Web Part

If you just want to modify an existing list with a custom rendering template, you can specify the JSLink property of any existing list by modifying it’s Web Part Properties and configure the "JS Link" property, like this:

image

If you configure the aforementioned property on the List View Web Part your list will automatically load your custom JavaScript file upon rendering.

Set the SPField.JSLink property in the Field XML definition

If you are creating your own field, you can modify the Field XML and have the property set through the definition like this:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">  
  <Field
       ID="{43001095-7db7-4219-9df9-b4b0f281530a}"
       Name="My Awesome Sample Field"
       DisplayName="My Awesome Sample Field"
       Type="Text"
       Required="FALSE"
       JSLink="/_layouts/15/Zimmergren.JSLinkSample/Awesomeness.js"
       Group="Blog Sample Columns">
  </Field>
</Elements>

Set the SPField.JSLink property using the Server-Side Object Model

Simply set the SPField.JSLink property like this. Please note that this code was executed from a Console Application, hence the instantiation of a new SPSite object:

using (SPSite site = new SPSite("http://tozit-sp:2015"))
{
    SPWeb web = site.RootWeb;
    SPField taskPriorityField = web.Fields["Priority"];

    taskPriorityField.JSLink = "/_layouts/15/Zimmergren.JSLinkSample/AwesomeFile.js";
    taskPriorityField.Update(true);
}

Set the SPField.JSLink property using PowerShell

If you’re the PowerShell-kind-of-guy-or-gal (and you should be, if you’re working with SharePoint…) then you may find the following simple snippets interesting, as they should come in handy soon enough.

PowerShell: Configure the JSLink property of an SPField

$web = Get-SPWeb http://tozit-sp:2015
$field = $web.Fields["Priority"]
$field.JSLink = "/_layouts/15/Zimmergren.JSLinkSample/Awesomeness.js"
$field.Update($true)

PowerShell: Configure the JSLink property of a Web Part

Note that this is what I’ve been doing in the sample code later on – I’m not setting a custom JSLink for the actual SPField, I’m setting it for the List View Web Part.

$web = Get-SPWeb http://tozit-sp:2015

$webPartPage = "/Lists/Sample%20Tasks/AllItems.aspx"
$file = $web.GetFile($webPartPage)
$file.CheckOut()

$webPartManager = $web.GetLimitedWebPartManager($webPartPage, [System.Web.UI.WebControls.WebParts.Pers
onalizationScope]::Shared)

$webpart = $webPartManager.WebParts[0]

$webpart.JSLink = "/_layouts/15/Zimmergren.JSLinkSample/Awesomeness.js"

$webPartManager.SaveChanges($webpart)

$file.CheckIn("Awesomeness has been delivered")

As you can see in the PowerShell snippet above we’re picking out a specific page (a Web Part page in a list in my case) and picks out the first Web Part (since I know I only have one Web Part on my page) and set the JS Link property there. This will result in the Web Part getting the proper link set and can now utilize the code in your custom javascript file to render the results.

So what does the JS Link JavaScript logic look like?

Okay, so I’ve seen a few ways to modify the JS Link property of a list or a field. But we still haven’t looked at how the actual JavaScript works or what it can look like. So let’s take a quick look at what it could look like for a List View Web Part rendering our items:

// Create a namespace for our functions so we don't collide with anything else
var zimmergrenSample = zimmergrenSample || {};

// Create a function for customizing the Field Rendering of our fields
zimmergrenSample.CustomizeFieldRendering = function ()
{
    var fieldJsLinkOverride = {};
    fieldJsLinkOverride.Templates = {};

    fieldJsLinkOverride.Templates.Fields =
    {
        // Make sure the Priority field view gets hooked up to the GetPriorityFieldIcon method defined below
        'Priority': { 'View': zimmergrenSample.GetPriorityFieldIcon }
    };

    // Register the rendering template
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(fieldJsLinkOverride);
};

// Create a function for getting the Priority Field Icon value (called from the first method)
zimmergrenSample.GetPriorityFieldIcon = function (ctx) {
    var priority = ctx.CurrentItem.Priority;

    // In the following section we simply determine what the rendered html output should be. In my case I'm setting an icon.

    if (priority.indexOf("(1) High") != -1) {
        //return "<div style='background-color: #FFB5B5; width: 100%; display: block; border: 2px solid #DE0000; padding-left: 2px;'>" + priority + "</div>";
        return "<img src='/_layouts/15/images/Zimmergren.JSLinkSample/HighPrioritySmall.png' />&nbsp;" + priority;
    }

    if (priority.indexOf("(2) Normal") != -1) {
        //return "<div style='background-color: #FFFFB5; width: 100%; display: block; border: 2px solid #DEDE00; padding-left: 2px;'>" + priority + "</div>";
        return "<img src='/_layouts/15/images/Zimmergren.JSLinkSample/MediumPrioritySmall.png' />&nbsp;" +priority;
    }

    if (priority.indexOf("(3) Low") != -1) {
        //return "<div style='background-color: #B5BBFF; width: 100%; display: block; border: 2px solid #2500DE; padding-left: 2px;'>" + priority + "</div>";
        return "<img src='/_layouts/15/images/Zimmergren.JSLinkSample/LowPrioritySmall.png' />&nbsp;" + priority;
    }

    return ctx.CurrentItem.Priority;
};

// Call the function. 
// We could've used a self-executing function as well but I think this simplifies the example
zimmergrenSample.CustomizeFieldRendering();

With the above script, we’ve simply told our field (Priority) that when it’s rendered it should look format the output HTML according to the contents in my methods. In this case we’re simply making a very simple replacement of text with image to visually indicate the importance of the task.

For examples of how you can construct your SPField.SPLink JavaScript, head on over to Dave Mann’s blog and check it out. Great info!

Summary

With a few simple steps (essentially just a JavaScript file and a property on the LVWP or Field) we’ve changed how a list is rendering its data. I’d say that the sky is the limit and I’ve already had one of my clients implement a solution using a custom JS Link to format a set of specific lists they have. What’s even better is that it’s so simple to do, we don’t even have to do a deployment of a new package if we don’t want to.

The reason I’ve chosen to do a Farm Solution (hence the /_layouts paths you see in the url’s) is that most of my clients still run Farm Solutions – and will be running them for a long time to come. And it wraps up a nice package for us to deploy globally in the farm, and then simply have a quick PowerShell script change the properties of the LVWP’s we want to modify and that’ll be that. Easy as 1-2-3.

Enjoy.

Follow me

Tobias Zimmergren

Founder / Consultant / Advisor at TOZIT AB
Tobias Zimmergren delivers high-quality articles about business and technology around the Microsoft scene.

Tobias focuses on advisory and consultancy for the Office 365 and SharePoint offerings from Microsoft.
Follow me
  • http://twitter.com/johnnliu John Liu

    This looks nasty for performance, if we need to call ctx.currentItem per row, when you display 1000 rows what’s the performance like? Older IE 7/8 is especially bad at JavaScript lockup/timeouts.

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi John,

      Honestly I haven’t tested the performance in various browsers or on lists with more than a few hundred items. But that’s a good point – I might spin up some tests to see if it affects the rendering process much and if it differs in various clients as well.

      • http://twitter.com/johnnliu John Liu

        I want to just say I love the fact that we have this function. But speed when templating in javascript is a thorny problem, and lots of js templating engines attempt to handle them differently with varying speed results. I’m just not sure whether MS is using an existing (fast) templating engine or did they build their own version that may (or may not) be very fast.

        Ultimately, it could all come down to guidelines and testing. If you use only max=20 rows there’s going to be no performance issues on any browser, but 1000+ rows I think user’s browser will probably choke.

  • David Mann

    Hey Tobias, Thanks for the plug of my blog post. It was kinda fun figuring all that stuff out. :-) I’ll have some new stuff related to the original JSLink post coming in the new year. Cheers!

    Dave

    • http://www.zimmergren.net/ Tobias Zimmergren

      Dave, thanks for the comment. My pleasure, you’ve got some killer stuff in there.
      Cheers,
      Tobias.

  • Pingback: SharePoint Daily » Blog Archive » Hybrid SharePoint Computing; Office 2013 Details; SharePoint 2013 Readiness

  • Pingback: Hybrid SharePoint Computing; Office 2013 Details; SharePoint 2013 Readiness - SharePoint Daily - Bamboo Nation

  • Amit

    Thanks for the nice article !!

    Our requirement is to render the UI of the list view as a
    Kendo UI grid, such that users can perform filtering, sorting, grouping and
    other features provided by kendo grid at the UI itself. The columns will be
    added by users in the list view at runtime and the same needs to appear automatically
    in the Kendo UI grid too.

    Using JSLink property, I am able to change the appearance of
    how a particular field renders inside list view.

    But is it possible to change the appearance of complete list
    view to render as Kendo UI grid, using the JSLink property. Looking for ideas
    on how to achieve the same.

  • baseic

    Hi, I just did something similar as you did above. And I see in your screenshots that you have the same problem as me. Namely that the checkboxes for “Completed” or as the view field really is called “Checkmark” stops functioning as soon as you add a custom jslink to the task list. It just shows “Yes” and “No”.

    Do you have any idea why this is happening? Could it be that we need to reference another script as well?

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi baseic,

      Interesting observation – I haven’t looked into that just yet. Please do let me know if you find anything on the subject. I’ll post an update here if I have time to dig around later. Since the values are still there I’m pretty sure there’s an easy fix for getting those boxes back.

      Cheers,
      Tobias.

  • Paul Noone

    Hi Tobias,
    I’ve adopted your example by uploading the js as a Javascipt Display Template to the masterpage gallery and then adding the JSLink path to my list view web part.
    Unfortunately I’m having no luck whatsoever. Is there something I’m missing here?

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Paul,
      There’s most likely something going on in your Javascript file or the files are incorrectly linked. You can always use Developer Toolbar in IE, Firebug in FF or the Chrome debugging tools in order to debug your javascript smoothly.

      Set up a breakpoint on the first line and take it from there – if the file doesn’t even get executed, something is wrong. If the script is executed but fails, you can find out the reason while debugging.

      Hope this helps.
      Tobias.

  • Anita

    How do I determine the web part number (using the powershell deployment of jslink), if I have a handful in different zones ?

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Anita,

      This varies depending on what you’re trying to do, and how you are doing it.
      Without additional details I can’t provide you with a sufficient answer :-)
      Cheers,
      Tobias.

  • Wes Preston

    Some other notes on the UI (JavaScript-capable ‘power-users’) side of things as well: http://www.idubbs.com/blog/2012/js-link-for-sharepoint-2013-web-partsa-quick-functional-primer/
    Wes

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hey Wes,
      Thanks for the link – good read!
      Tob.

  • Pingback: SharePoint Development Lab by @avishnyakov » Custom Field Type for SharePoint 2013 – VISA card field sample

  • Pingback: SharePoint Development Lab by @avishnyakov » Custom Field Type for SharePoint 2013 – Custom “Quick Edit” mode rendering

  • Pingback: Applying JS Link on Task Lists Breaks the Default Rendering of the Checkboxes - Elio Struyf - Elio Struyf

  • Pingback: Using the JSLink property to change the way your field or views are rendered in SharePoint 2013 | @SPSamer

  • Pingback: SharePoint Development Lab by @avishnyakov » I am speaking at Darwing SharePoint user group – Introduction to client side rendering in SharePoint 2013

  • Arne

    Hi,
    great article. I tried to use it as a JSLink in a webpart. I have place a link in every blog post, so i want to use it to override the body field in a blogpost-list.
    Teh problem is that it is not working correct. For example on the default.aspx with the latest posts the link appears, when i click in one blog it disappears, then i refresh and it appears. What could be the problem.
    Arne

  • paulhunt

    Hi Tobias,

    Just wanted to add some info in a blog post of mine. I hit a problem at a client where we were wanting to use Display templates on two lists on the same page. If they both come from the Custom List Template and a baseviewid of 1, then both list views get affected.

    My fix overrides the ootb RenderListView and fixes up the baseviewid of the webpart we want to affect. Hope it may be useful to someone.

    Paul.

    http://www.myfatblog.co.uk/index.php/2013/09/listview-web-part-issues-with-jslink-and-display-templates-a-solution/

    • http://www.zimmergren.net/ Tobias Zimmergren

      Nicely done Paul. Appreciate the post :-)

  • Ivan

    Hello Tobias,
    as I guess, it is that it is not possible to get the value of a column which does not belong to the view so how could I hide this column on rendering ?
    Thx

  • Iván Paredes Sanmartín

    Hi Tobias,

    I’m trying to add JSLink to default list new form adding this markup:

    But when deploy my feature the JSLink webpart property show as blank. ¿Do you know where could be the error?
    Thanks!

    • Srikanth

      HI Ivan,

      Did you find a solution for this issue?

  • maklei

    Many thanks for this sample! is perfect work! have you any tutorial how change the header? add border, bold…. thanks in advance

  • Pingback: SharePoint JS Links | Share your knowledge

  • Pingback: SharePoint | Bits and Bytes » SharePoint 2013 Quick Edit JavaScript Validation

  • Pingback: Keith Tuomi – SharePoint Server MVP SharePoint Calculated Column Formulas » Keith Tuomi - SharePoint Server MVP

  • Srikanth

    Hi Tobias,
    I successfullly implemented CSR using JSLink option listview webpart. But the issue is filtering and sorting stopped working after applying the JSLink. Did you face the same issue?

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Srikanth,

      Yes I’ve seen some issues when using JSLink, but haven’t dug very deep into it. Pop on over to http://www.mssharepointforums.com and you should get a quicker reply :-)

      / Tobias.

  • Arham

    Hi Tobias,

    I have a custom field and i am applying custom javascript(JSLink) to change how the data is shown on the Listview page . Everything is working fine, my field is being rendered according to my need. But this only happens as long as i am using the default viewstyle. As soon as I change the viewstyle of Listview page to shaded(), javascript stops working. If i turn back to default viewstyle, javascript starts to work again. Any suggestion on how i can apply apply JSLink with shaded viewstyle?

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Arhan,

      I think the best place for this question is http://www.mssharepointforums.com in order to get a reply reasonably fast :-)

      / Tobias.

  • Shivank Kaul

    Brilliant, thanks for that..

    • http://www.zimmergren.net/ Tobias Zimmergren

      Thank you for commenting. I’m glad you liked it.
      Regards,
      Tobias.

  • Pingback: SP 2013: Measuring performance on the JSLink property in SharePoint 2013 - Tobias Zimmergren's thoughts on technology and business

  • Pingback: SharePoint 2013 JSLink property | Tjen Sharepoint Blog

  • Martin

    Hello Tobias,

    Do you how we can specify to use the default field rendering? Let say in your example that the priority is not High, Normal or Low and for this case you would want to use the default sharepoint rendering for this field.

    Regards.

  • Pingback: SharePoint App jslinks | Share your knowledge

  • Pingback: SP 2013: Using the JSLink property to change the way your field or views are rendered in SharePoint 2013 | Share your knowledge

  • Robert Habicht

    The icons do not show whenever I navigate to my list using the quicklaunch bar to the left.
    The javascript file is requested via XMLHttpRequest and the server returns 304.

    As soon as I reload the page the javascript is being executed. Is it just me?
    I realized this only happens if you update your page via start.aspx (http://sharepoint/_layouts/15/start.aspx#/Lists/SomeList/AllItems.aspx)

  • Darshit

    I have added a jslink field in my custom list on this filed click event i am opening one application page
    ,page is opening correctly but when i applied filter on list then click on jslink field a AllItems.aspx is refreshed and filter is no more….can you please tell me what is a poblem…