Friday, July 24, 2015

Introduction to Client-Side Rendering in SharePoint 2013

One of the best new features for SharePoint branders is Client Side Rendering. In this blog, I’ll go through what it is, how Client Side Rendering (CSR) can be used, and some tips I’ve found for debugging and developing it.



What is Client-Side Rendering?

Client Site Rendering is simply when the data is transformed using the client rather than the server. This means using client-side technologies, such as HTML and JavaScript. It allows us to style SharePoint elements using JavaScript, rather than having to write XSLT. You can use it to style complete List Views, Fields, Search Results and more. This makes it a lot simpler and more intuitive, especially for web developers who haven’t used SharePoint before.
When talking about Client Side Rendering in SharePoint, there’s really 2 mechanisms; search Display Templates, and JSLink. From MSDN : “Display templates in SharePoint Server 2013 are templates used in Web Parts that use search technology”… (http://msdn.microsoft.com/en-us/library/jj945138.aspx). They allow us to completely transform the way search results look, which gives an endless possibility of what they can be used for. A common example would be in the use of Blog rollup. Because the results are based off of search, it allows us roll up results from multiple site collections, and even from other farms, or non-SharePoint sources.
JSLink on the other hand is a property available on many SharePoint objects, including Fields, Lists, Views, and Content Types. In its simplest form, the JSLink property simply adds a JavaScript file to the page. Depending on the JavaScript, this could then do anything – either related to the object of which it was attached, or something completely irrelevant if desired.
Display Templates have been covered quite a lot by Microsoft already, so the majority of this blog post is talking more specifically about List rendering with JSLink.

Advantages of Client-Side Rendering

There are a few advantages of using Client Side Rendering VS XSL.
  1. Performance – Because the rendering is done Client Side, the burden is taken away from the server. This means that the pages can load faster when using CSR.
  2. Ease of Development – Let’s face it: nobody really likes XSL – especially in SharePoint. All web developers should be familiar with JavaScript, which makes Client Side Rendering a lot easier to pick up. This should mean reduced development time, and less bugs.
  3. Flexibility – You can chose to overwrite just a particular field, the header, footer, or the entire view. You can also extend it; you’re not limited to using just SharePoint JavaScript to process the list, you can use the whole power of JavaScript, as well as any plugins such as jQuery.

Disadvantages of Client-Side Rendering

Having mentioned the advantages, it’s only fair to mention the disadvantages:
  1. Compatibility – As it’s rendering on the client browser, you have less control of what’s happening. If the client does not support a function you use, then that user will get a different experience to other users. With XSL, this was not the case, as the server dealt with it, ensuring everyone got the same HTML back.
  2. SEO – This is only really relevant for public facing sites, however, rendering everything with JS is a bad idea for public site SEO. Crawlers are less likely to understand it, and may not display that content in search.
  3. Performance – Although this was listed as an advantage, it is also a disadvantage. If the client computers are particularly old, or under spec’d, complicated JavaScript could make the browser hang, or in particularly bad cases, crash completely.
The good news is that you don’t have to use the JSLink yet if you don’t want to. All of the web parts still support XSL, so if you feel more comfortable doing it this way, this should still work. You can simply select “Server Render”, and point it to a valid XSL file.


How to use JSLink

If you’ve read this far, I’ll presume you’re still interested in using the JSLink property, and are wondering how it’s done. This blog post covers the steps required to use the JSLink. I’ll summarise the steps below:
  1. Create your List (Including Views)
  2. Create your JavaScript file
  3. Set the JSLink property of your Web Part
Although this is very high level, it should be very familiar if you’ve ever done this before in XSL; there’s nothing particularly different in the process between this and XSL.

Creating a Progress Bar for Task Lists with JS Link

As a demonstration of what can be achieved with the JS Link, I’m going to step through creating a simple progress bar for a Tasks list, as pictured at the beginning of the blog. The first step is to create a standard Task list. You can do this all though the UI, or deploy the list via a WSP built with Visual Studio if you wish.
The next step is creating the JavaScript. The file can be created anywhere on your site. Remember that all users will need permissions to read this file, else the rendering will fail. I’d recommend putting it in the Master Page or Style Library if you only plan on using it in 1 site, or if you’re deploying using Visual Studio, the Layouts folder may be a good place to put it.
Once you’ve created the file, it’s time to add some code.
To create a progress bar, we need to override the “% Complete” column. Using Wes’s demo as a base, we can add the following code:

This function is building up an object, which is then used to register a template override. The object takes the following properties:
  • View
  • Header
  • Body
  • Footer
  • Group
  • Item
  • Fields
  • OnPreRender
  • OnPostRender
As I only want to override the % Complete column, I’m going to use the Fields property. The other properties can be used to override different elements of the web part, including the header, footer and the whole item. You can also use the OnPreRender and OnPostRender properties to call functions before and after rendering a template. You can see an example of overriding the Header, Footer and Item over at MSDN
The Fields property takes the format of:
overrideCtx.Templates.Fields = {FieldName {Scope : Override}}
  • FieldName – This is the internal name of the field you want to override.
  • Scope – This defines when to override the field. The choices are “View”,”DisplayForm”,”EditForm”, and “NewForm”
  • Override – The actual override. This can be a HTML string with JavaScript embedded, or a function to be executed. In the former, it should be in the format: “<p> <#= ctx.CurrentItem.PercentComplete #></p>”, where “<p>” is just some HTML, and everything enclosed in “<#= #>” is JavaScript to be executed.
For the override, I’ve chosen to use a function. I find this a lot easier to read, and also to debug when it doesn’t behave. For this, I’ve added the following code:
The first line is getting the value of the field. All of the information about the field is contained in the ctx.CurrentItem object. We can supply the name of the field to get the value of the PercentCompelte field. Once the value of the field has been obtained, all spaces are removed using the replace method, to ensure it forms a proper value for the CSS. Then, 2 variables are created holding strings to be used as inline JavaScript. This means that the actual value can show up when somebody hovers over the progress bar. Finally, a HTML string is built, with 2 divs; the inner of which is using the percentComplete variable to assign its width, and a p tag which contains the text of the value. In a more realistic scenario, all of the inline CSS should go into an external style sheet and referenced from the page. All of this is returned from the function.

Set the JSLink property of a List View Web Part

This is a very straightforward step, and is exactly the same as how you would do it if you were changing the XSL of a list view web part. Edit the page, then edit the web part. Under “Advanced” there is the JS Link property. In here, just type the link to wherever you uploaded the JS file to.
Note in the picture, that I’m using the ~sitecollection token as part of the link. I can’t find any documentation on MSDN around this, however if the JS link is made root relative while pointing to a document library (e.g. /style library/template.js), the rendering switches back to the default rendering, and the file is not included. I’m not sure if this is expected behaviour, or if there’s something going wrong with my environment – just watch out for this if you can’t seem to get the template to register!
The JSLink property also accepts other SharePoint tokens, which gives you complete flexibility of where you deploy your JavaScript to:
  • ~site
  • ~sitecollection
  • ~layouts
  • ~siteLayouts
  • ~siteCollectionLayouts
Once the property has been set, your web part should look like this. As you can see, the first progress bar is being hovered over, resulting in the actual number being displayed:
You can see a live demo of this field on the page here, and download the JavaScript file here.

Debugging the JavaScript

As you work with the JSLink and Client Side Rendering, sooner or later you’re going to find something isn’t working. Working out what’s happening can seem a little tricky to begin with, so here’s a few tips for debugging the script.

Check the Script actually exists

This one sounds stupid, but the first thing to do is check that the script exists. Make sure that when you view the source of you page, you can see the <script> tag which points to your file. Also make sure that when you try to download this, that it returns the right version of the file. As I mentioned above, when I left out the “~sitecollection” token from the JS Link property, my script just wasn’t on the page, so give this a double check first.

Alerts and Logs

To quickly make sure that your override is getting run, you can throw an alert in. I’d tend to avoid alerts for this sort of work however. Imagine you have a list with 100 items in, and you put a couple of alerts in the override function. This is going result in hundreds of alerts, and a lot of annoyance. Instead, I’d use console.log to output the messages to the developer toolbar. This is a lot cleaner, however has the disadvantage of not pausing the script while you look at the values.

Debugger

This is my personal favourite way of debugging any JavaScript. It’s really easy to use, and can give a lot more information than an alert. Debugger adds a breakpoint to your script, which means you have a chance to inspect the objects in their current state. If you’re using Chrome, and have the Developer Toolbar open when you load the page, it will automatically stop at the debugger statement, giving you a chances to investigate any issues.

Once the JavaScript has paused, Chrome allows you to live edit the script, and also run other scripts in the console. Chrome also has the advantage of giving an autocomplete. For example, below I typed “ctx.Currrent” and its offering suggestions of what I might be looking for. This is useful if you’ve forgotten the name of the property you want to look at.

You can also view all of the properties of an object by typing it in and expanding it. Below is the view of the ctx.CurrentItem object, which lets you see all of the properties values. From here I can see for example that the DueDate field is an empty string, which could have caused an issue if I was trying to convert it to a JavaScript date object.

Summary

This blog post has been a lot longer than intended, and I’ve barely scratched the surface on what they can do. I’ve quickly ran through some of the advantages of using them, including the potential performance benefits and their flexibility. I’ve shown an example of creating a progress bar using CSR, and also shown how to debug the JavaScript when it misbehaves.
In future blog posts I’d like to cover overriding the whole view, to create a completely branded display of a list, and how it can be used to customise edit forms. Also moving towards search, I plan on looking at creating Display Templates to customise the Search Results and Content by Search web part, as well as customising the Refinement Panel web part, all using JavaScript.

No comments:

Post a Comment