JS Link for SharePoint 2013 Web Parts–A Quick Functional Primer

JS Link is a new web part property in many SharePoint 2013 web parts.  It allows users and developers to create Client-Side Rendering (CSR) solutions within SharePoint 2013.  In other words, it allows alternate formatting, data and functionality to be manipulated within a web part.  It is one approach that will help replace the data view web part (DVWP) functionality that was used in SharePoint 2010 and SharePoint Designer 2010.

For example, CSR scenarios can edit how specific fields are displayed, how whole web parts are formatted and what functionality is available.  And these are just a few simple examples.  There is a lot of potential for what can be done.  My session at SPC12 just scratched the surface while others dug much deeper.

Something to note is that using JS Link to implement CSR functionality is easy and reversible.  If you don’t like what it’s doing to your web part you can easily change the JS Link property back (blank it out) and your web part will go back to it’s default format.

The CSR approach is more developer-focused than power user-focused.  There are, however, a few simple things that can be done that I think will be accessible to power-users that have some comfort level with code, specifically JavaScript, HTML and CSS.

So, here are the main components you need to make CSR work with out-of-box web parts – nothing fancy – using JS Link in SharePoint 2013:

  • Create a JavaScript override file
  • Upload the JavaScript file to the Master Page Gallery
    • Set the content type and properties of the file in the Master Page Gallery
  • Set the JS Link property of the web part to point to the JavaScript file

Sounds easy enough, but there are a few details to sort out to get everything synced up.  Additional details for each step are listed below:

Create the JavaScript file
In these examples, JavaScript is being used to override different things – how data is displayed and what content is displayed.  For starters we’ll override a specific field in a view.

During my session at the SharePoint Conference (SPC12) I used a few simple examples that are a good starting point.  EXAMPLE JS FILES

In the first example, we get everything in place and make sure that it’s working.  We start with a standard view (AllItems) that shows text fields, and then use the JS Link functionality to override a single column – displaying different text than came with the view.  We are replacing whatever the ‘MoreText’ column contained with the word ‘Animal’.

image

As the notes in the sample script mention, the Fields override works specifically with individual fields.  You can specify a single field, or multiple fields.  For each field (column) override, you need to identify the field being overridden and the replacement value.

When identifying the field name, take note that you need to use the internal name for the column, which may not be the same name that is displayed.  In some cases this is true, but not all.  See my post on finding the internal column name.

The ‘View’ component of the command is in reference to the type of template being overridden – in our case the view.  There are also options for the NewItem, EditItem and DisplayItem forms, but we won’t cover them in this article.

The last piece of the command for each field is the override value for the field.  This can be a static value – as in the first example – a variable, or HTML and the value, allowing you to style the value.  You can also call a function within the script to do more complicated logic – such as conditional formatting – but for the field.

Note: The following example code is shown with the Before and After output of the sample web part.  The changes will not go into effect until you’ve put all the pieces in place – the steps which are listed after the sample images.

Example 1:  Uses a static value to override the field value.  ‘Animal’ will replace the ‘MoreText’ field value for each list item in the view.

image

Before:

image

After:

image

Example 2:  Displays the true value of the MoreText field, but formats it (bold) by wrapping it in an HTML tag.

image

Before:

image

After:

image

Example 3:  Calls a function that formats the value that overrides the field data.  In this case it uses a conditional to determine what data is displayed.  This could just as easily be used to implement conditional formatting for the field by keeping the field data as in Example 2, but formatting it differently using HTML tagging.

image

image

Before:

image

After:

image

Example 4:  Uses a different override.  This example uses the Item override instead of the Field override.  Using the Item completely overrides the web part and requires the Header and Footer overrides as well.  In the example here, the data is displayed in an HTML list where the open tag is in the header and the closing tag is in the footer.  Each item is then an item in the list.

image

image

Before:

image

After:

image

One other note on the code.  We aren’t getting into details with these settings, but a few of the sample scripts also include settings for BaseViewID and ListTemplateType.  These settings are not required, but if you are using JS Link on a page that has more than one view, these properties control which web parts are affected by the JavaScript code.

BaseViewID is the view ID for the list with 1 being the AllItems view.

ListTemplateType is the ID for the type of list template is used such as Links List, Task List, Custom List, etc.  A list of these types in 2013 can be found here:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.listtemplatetype(v=office.15).aspx

Upload it to the Master Page Gallery

The script files need to be uploaded to a place where they can be accessed by the web part.  Depending on what version of SharePoint you’re using and what your scope is, you will need to determine the best location for the scripts.  In our case we used Office 365 for a test bed and only want to use the scripts within our site collection, so we are uploading the files to the Master Page Gallery.

As each file is uploaded, the content type of the file will need to be changed to ‘JavaScript Display Template’ and the required fields will need to be completed.

In our examples, the Target Control Type is ‘View’.

The Standalone value is ‘Override’.

And the Target Scope is the relative URL of the site collection we’re customizing in the format: ‘/sites/d1’.

image

For our example, upload each of the 4 sample files so that you can see the different examples at work.

Add the JS Link property that points to the JS file

Finally, edit the web part properties you are trying to edit.  This may be web parts on a web part page, or a web part on a standard view page.  Edit the page, then the web part.  Expand the Miscellaneous section and edit the JS Link property using the following sample format to point to the location of the JavaScript file you are using for the CSR override:

~site/_catalogs/masterpage/csr_overridable_demo1.js

Save your changes.  If everything is working, the changes should be immediately visible.  If you still need to edit the JavaScript to match your specific column or example, edit the file using SharePoint Designer.

Edit the files using SharePoint Designer 2013

Developers have a number of code editing tools at their disposal and can use Visual Studio or others.  Non-developers can use SharePoint Designer 2013 to view and edit the JavaScript once it has been uploaded to the site.

If you haven’t already edited the files to match your specific list column names, start SharePoint Designer and open the site collection where you are doing your testing.

From SPD you can edit and save your JavaScript files live.  After you make a change to the JavaScript file, refresh the browser page and your changes should be reflected – assuming everything is correct.  Smile

Wrap-up

Sorry for such a short and unpolished post – there is a LOT more to talk about regarding JS Link and SharePoint 2013 –  but I wanted to get this out for people that attended my #SPC064 session at #SPC12 or who started hearing the rumblings about JS Link this week while at the conference. Hopefully this allows you to get started playing around with the power of JS Link.

Lots more to come!

Notes:

  • JS Link is not only used in web parts, but can also be set and used when creating custom apps, etc.  This post is just covering the specific example when using the web part property.
  • Be sure to take a look at the HTML that is produced by the page once you have your CSR in place.  Some approaches in the CSR may not jive well with the existing page code. You  want to avoid conflicting tags, etc.
  • JS Link override will not work if the form has been edited in SPD.

66 comments

  1. Hi Wesley,

    I’ve been working on a MOSS2007 sytem for some 3 years now using a fair amount of JavaScript, CSS and HTML in web parts to render changes client site to pages, etc.

    My employer is in the process of upgrading to SharePoint 2013 and am in the process of trying to work out how to make client site rendering changes on pages and hoped your post above might help me in my endeavours.

    I’ve implemented exactly as described in your article but to no avail. One this I did wonder was what value should be set for the ‘Target List Template ID’ when uploading the .js file as a Javascript Display Template. You on screen example has a value of 107 and I would like to know if this is relevant and where you got it from.

    Regards,

    David

  2. Thanks for the great tut. I can make this work with my custom announcements list using the first 3 examples, however with the 4th example (the one I actually want to use) I get ‘undefined’ outputted for any field other than the Title field. Any ideas?

  3. 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. 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.

  4. Hi ya,

    Great post. We’ve been trying to find the simplest way using SP2013 and Office 365 to style lists in a consistent way. What we have found though is that all the web parts on the page seem to get the style applied and not just the one you add the JS Link to. Any ideas what is going on? Or how to avoid this behavior?

    Cheers,

    Rich

    1. Rich,
      I didn’t cover it in this post in much detail at all (just a mention), but there are additional controls you can use to target the content you want controlled. If you look in the first code sample shown there are a couple of commented out lines that will help you:

      overrideCtx.BaseViewID = 1;
      overrideCtx.ListTemplateType = 100;

      These are pointing to the specific view you’re targeting and the list type – the list definition.
      You can find a list of the List Template Types here: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splisttemplatetype.aspx

      Let me see what else I can find on the BaseViewID. I just played with it by trying a few values. It needs to be greater than or equal to 0 and less than 255.

      Wes

  5. Hi, do you know of any way to find the BaseViewID of a list view created via the browser, that doesn’t require going to the schema.xml file? I’m trying to find a way without having to open the xml because I don’t currently have access to SPD 2013, and just have the site network mapped.

  6. Wes, thank you for a great post. I am trying to build on your examples, which work well. In my own experiments I can change how all fields are rendered, except for the Title field. Do you have any insight? I just want to change even just the text of the title field from say a part number (which is useful in most cases) to a one line description of the part (so that the user can click on it), which is useful in a specific case. I would like to keep the functionality of the Title field to be able to click through to the Forms.
    Any hint would be highly appreciated by this stranded power user,
    G.

  7. Hi,
    I have followed your steps exactly but it doesnt work – after i have added the js-link to the web part and pressed apply, the list shows: [object Object] on every row and if I close the web part properties the list is back to normal again and no changes are made. I have checked that I have the correct column name and so on but I’m no programmer so I can’t figure this out by my self… do you have any idea of what I’m doing wrong?
    Thanks for your advice!
    Regards Jennie

  8. Thanks it was a great post. Please provide more links and examples related to SP2013 Webparts customization using JS link. Thanks in advance.

  9. Great post! I’m trying the 4th approach for modifying the entire layout and it works great. The only issue is that if I have multiple listview webparts in the page for the same library, and I try to apply different JS Links, only one JS file gets applied to all the ListViews. I guess the BaseViewID and ListTemplateType are always the same. Any idea on how to accomplish this?

  10. Jennie – I got the same issue when I set JS Link property for the first time. It seems like something is not properly refreshed in edit mode.
    This is what I did to resolve it:
    – In the webpart properties, click “Customize Current View” link, under Views dropdown.
    – In the new window click OK so the current View is refreshed.

    Hope this helps.

    -Luis

  11. Thanks for the article. I don’t understand where this ctx object that is passed into the CustomItem function comes from. I don’t see it being declared anywhere or anything. For me, i followed the post exactly, and i get a console error saying “TypeError: ctx is undefined”. Am I missing something? If i remove the function and just put some text directly in the field (like overrideCtx.Templates.Item = ‘test’;) it works and modifies the view.

  12. I am working with a client, and I am working for the business, not IT. So I do not have access to the Master Page Gallery. So I tried to create a library, called it scripts, and put the 4 script files in the scripts library. Then I modify the web part property to “../scripts/csr_overridable_demo1.js”.

    I know it is finding the script, becuase the behavior changes. Unfortunately, the screen goes completely white and the page seems to be frozen. Is this something I should be able to do?

    1. I believe you should be able to put the scripts in other locations – I’m pretty sure I’ve seen other posts along those lines but I haven’t done it myself. Any chance the script you’re using is messing with the page? It’s really easy to leave an open tag or something that interferes with existing pieces of the page…

  13. Thanks Wes, great post! Question, what if instead of uploading the JavaScript files to the Master Page Gallery you wanted to deploy the JavaScript files with Visual Studio to the Master Page Gallery but still have them registered as JavaScript Display Templates? I’ve been trying to do this with a Module and elements file like this, but the Target Control Type, Standalone mode, Target Scope, and Target List Template ID properties are not being set but the Content Type, Name, Title, Description and Hidden properties are set. I have found zero documentation on this so I’m guessing a bit.
    Here’s an example:

    If you have any thoughts or know where to find the documentation let me know.
    Thanks,
    B

  14. Hi Wes, l got undefined error when l want to output
    ctx.CurrentItem.Body , however it work fine for ctx.CurrentItem.Title
    I got ‘Body’ the column field name from the list library. How can l find out the proper name sharepoint understands?
    Thank you!

  15. I’ve tried what I believe is EVERYTHING. I cannot get a JS Link to fire. I’m hosted the scripts in the MasterPage Gallery, /JS, in the Page Library. I’ve read everything I can get my hands on. I’ve taken these scripts down to:

    (function () {
    // Initialize the variables for overrides objects
    var overrideCtx = {};
    overrideCtx.Templates = {};

    alert(“Override Call Worked”);

    })();

    … and still nothing.

    Is there perhaps another setting somewhere (in Central Admin? SPD?) that needs to be set to activate JS Link?

  16. Hi Wesley,

    Very nice article. I have one question –
    If on a page I have 2 or 3 custom lists(Same List Template Type) and I want to show different look of each other using same default view(Same base view ID), then how can I restrict the separate JS link to specific List View web part?

    Regards,
    Prasad

  17. Hi Wes! This is a great post and an excellent stating point… I was hoping you could shed some light on something for me. The jslink field does not seem to do anything until I open up the view in SPD 2013 and select “Customize XSLT” from the menu. I don’t have to actually make any changes after that, I just have to let it generate the XSLT and leave it in there. If I revert the XSLT, then the jslink continues to be ignored. Any idea why this is happening? Any feedback much appreciated!
    Thanks,
    Sean

  18. In trying to override the Body field on a Discussion List, I find that the simple
    overrideCtx.Templates.Fields call sets the whole Subject view back to the basic Item View, which is not what is desired at all. Any idea about the mechanics of this and how we can keep the rest of the view formatting? Is there something completely inconsistent in the Subject view of the Discussion List that just won’t make this possible?

  19. Thanks Wesley, I’m learning Client-Side Rendering, I found your article very helpful, it help me to be on the right way. Also these MSDN code samples help me a lot,

  20. Hi I tried using this link but I can’t see any modifications to the web part on the page is there will be problem because I am not using office 365 sharepoint. sharepoint 2013 on primeses I am using.

    1. JS Link and CSR work on both O365 and on-premises. If you’re not seeing changes to your web part, it’s likely something isn’t set up correctly. The two most common issues I’ve seen are that the JS Link property isn’t pointing correctly at the JavaScript file, OR that there’s an error in the JavaScript itself. ANY error in the JavaScript will cause SharePoint to ignore the JS Link content.

    1. I don’t see why you couldn’t create a table-like structure with the Item override. I’m not sure what you’re trying to do with the content Query web part though. JS Link works with views and forms, I’ve not seen it used within a CQWP. You’d probably use a different approach within them.

  21. For anyone else experiencing the issue where the override doesn’t appear to do anything, check the JSLink value in the web part properties. By default, SP2013 removes the root URL and uses a relative path. Adding the sitecollection variable to the beginning of the path fixed it for me.

    Broken: “/_catalogs/masterpage/display templates/mytemplates/template.js”
    Fixed: “~sitecollection/_catalogs/masterpage/display templates/mytemplates/template.js”.

  22. Thank you to this post!

    Just a clarification for people who are like me head area ^^:
    1) follow directions for entering the url specified in this post. (|site or ~siteCollection ex:~site/_catalogs/masterpage/)
    2) When adding a webpart to a list page, a view is created and assigned to this webpart … If you optenez ‘Undefined at places the value of the fields, switch back to normal view and the answer will have to be available to you.

  23. Hi there – I couldn’t find “JavaScript Display Template” as content type while setting properties for the js file on uploading to the masterpage gallery. Please help.

    Regards,
    Khushi

    1. Khushi,
      You don’t need to worry about setting the content type. Just upload the file and you’re good to go. I need to update the original ‘primer’ post to reflect additional findings we’ve had since the original article. JS Link doesn’t care how a file is stored in the library, just that it can get to it.

      Thanks!

  24. Hi,
    I have followed your steps exactly but it doesnt work – after i have added the js-link to the web part and saved, the list shows: [object Object] on every row and if I close the web part properties the list is back to normal again and no changes are made. I have checked that I have the correct column name and have tried changing the path to the file with both ~sitecollection and ~site, but I guess the webpart is not able to get to the file at all. Do you have any idea of what I’m doing wrong?
    I am saving the file in the master page gallery as a Javascript content type file.

    Thanks!

  25. Great Summary (I even notice it has been directly copied onto other Blogs !! )

    I have two questions relating to this method …
    1. Why do you need to put these into the Master Page library with all of these settings. Why can’t this be put in to a Site Assets library for a subsite if I am trying to render a subsite list specifically ?

    2. I notice you have to get the exact field name – but Sharepoint seems to ensure this is Unique across the site collection so I can’t have a field name StatusIndic across multiple lists allowing for the rendering to be applied to that type of field if it is used across more than one list ? ( I am doing this all with SP OOB – not using Designer or any other development tool – just using the native SP UI)

    thanks,
    R.

  26. Hi all,

    I had a similar request and had to learn Client Side Rendering functionality to customize some BI visualizations in SharePoint. As most of you, I had to make a very steep learning curve to accommodate the request. Here is what I found:
    – It requires technology (that would be SharePoint JSOM) insight,
    – Overall JS proficiency is on need to know base. You simply have to understand the mechanics of it, but you don’t have to be a world champion.
    – Forget about forcing JS to be C#. It is not and will never be a object oriented language. Get used to Callbacks and little bit of spaghetti code.
    – As stated before, it really does not matter where you put your JS script file as long Web Part can connect to it (SiteAssets, MasterPage gallery, Custom library, etc…)
    – Defining Contet Type for the script is waste of time. No effect what so ever!
    To make a long story short here is a working example of CSR that taps in on PostRender event of ListView WebPart rendition process:


    (function () {

    // jQuery library check if jQuery needed
    // Fallback to loading jQuery from a CDN path if the local is unavailable
    (window.jQuery || document.write(”));

    var listViewContext = {};
    listViewContext.Templates = {};
    listViewContext.OnPostRender = [
    ListViewOnPostRender
    ];

    // This is the important part!
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(listViewContext);

    console.log(“TemplateOverride done!”)
    })();

    function ListViewOnPostRender(ctx) {
    console.log(“PostRender!”);
    }

    Now, as for the field names, one have to understand that SharePoint operates with 4 types of column names/titles:
    – Name
    – Title
    – InternalName
    – StaticName

    There is a purpose for all 4 of them, but the trouble starts if they differs from each other (e.g. language variations, friendly naming conventions, etc…). To be able to see those “undercover” names/titles you can:
    – Use PowerShell scripts to inspect the list
    – Use 3rd party tools to do it for you. Codeplex is your friend: SP Client browser

    Once you get hang of it it actually becomes fun to work with and an ocean of opportunities.

    Thanks!

  27. Wow I know you said that you wrote this up quickly, but it’s great and this is the best walk-through of the JSLink that I’ve been able to find.

    I’m having an issue – when I apply the code to a page just using a Content Editor Webpart, it works perfectly. However, when I add the script as a JSLink, nothing happens – the script does not even get called.

    Is this an issue that comes up much?

    1. Matt,
      I hope you’ve found the answer by now… 😛 Poor lag on my part catching up with comments. Apologies. To answer the question for you and others – yes. It’s pretty common for first attempts to get JS Link working to fail. I’d say the most common issues are:
      1. The ‘token’ path put in the JSLink property isn’t correct – not pointing to the correct file location so the code doesn’t get called. This is why I use a pretty boilerplate file to start with and include the JavaScript ‘popup’ to verify that my file is being called before I do much of anything else.
      2. Something is wrong in the JavaScript syntax so SharePoint skips the entire file like it doesn’t even exist.

    1. The ‘easy’ answer is if you’re using a custom form created in SharePoint Designer 2013 – you can set the form as the ‘default’ version of the form you’re creating (New, Edit, Display) and SharePoint will take care of the rest. Anywhere you’re calling the ‘new’, ‘edit’, or ‘display’ (or ‘view’) form SharePoint will get the default form for you using all the existing UX.

      If you are creating a real custom form – then you can build a link using the item ID and link to the new form that way. Still a field override – text is easiest – and build the URL string with the items ID in the string. I’ll see if we can come up with a quick example here soon…

Leave a Reply to jamie Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.