Overview of SharePoint Client Side Rendering (CSR)

What is Client Side Rendering (CSR) in SharePoint? CSR is an API whereby Microsoft has pushed much of the process of rendering raw data as HTML off the server and onto the client (i.e. the browser) in the form of display templates (JavaScript) in SharePoint 2013 and later. It is a replacement for much of the XSLT that you may have written for previous versions of SharePoint to modify forms, views, and search results. This XSLT was processed on the server, and if you went nuts with this it could have a serious negative impact on the performance of your farm.
 
So, what can you do with CSR? You can develop display templates to modify list forms, views, and search results. As you might imagine, that’s a pretty big topic, so this post (and several follow up posts) will talk about overriding the rendering of fields in list forms. Eventually, I plan to post about view and search display templates as well.

The first thing you need to figure out is how to get some JavaScript injected into the page so you can override some of the form rendering. There are different solutions for this, so lets look at some, specifically for loading CSR templates to modify the rendering of fields in forms:
 
  1. You could just insert a content editor into the form. This is easy enough, but is not a great solution because you’re often going to want to modify the rendering of a field in multiple forms (new, edit, and/or display). So you’d need to add a content editor to each form. And you may want to modify the rendering of a site column, anywhere it appears in the site collection, which would mean you’d need to modify up to three forms in each list where the field is used. This could get out of hand in a hurry.
  2. You can create a script link to load the JavaScript at the site or web level. This is a very easy solution, but also not ideal for our purposes, because it will load our JavaScript on every page in the site collection or site, and we really only need it loaded on certain forms. There are times where this might make sense, for instance if you’re using jQuery in a bunch of customizations that are loaded throughout your site collection, then it might make sense to load it as a script link. But loading all CSR as script links generally doesn’t make sense.
  3. You can load the JavaScript using JSLink. This is so the right solution most of the time that many people seem to think CSR and JSLink are the same thing. They are not, and you need to understand the difference to use them together effectively.
This post is part of a series on Client Side Rendering:
 
  1. Overview of SharePoint Client Side Rendering (CSR)
  2. Creating Cascading Lookups with SharePoint Client Side Rendering (CSR)
  3. Setting the JSLink Property of a Field Using JavaScript
  4. Creating an Autocomplete Client-side Rendering (CSR) Template
  5. Dynamic CSR (Client-side Rendering) Templates
  6. A Full-Fledged Client-side Rendering (CSR) Template, a Rating Field
  7. Tabbed Forms with Client-side Rendering (CSR)
  8. An Accordion View, Custom List View Display Templates (CSR)
  9. CSR on Steroids and the Amazing Technicolor Text Boxes

So What is JSLink?

Just for yucks, I just went to google and searched for “What is JSLink”. The summaries for the first three results I got are:

JSLink is a new approach combining JavaScript, HTML and CSS elements to customize the look of a SharePoint list views, list forms, and can control the rendering of fields. JSLink was introduced with SharePoint 2013.

JS Link property is a great new addition in SharePoint 2013 with which user’s can Control Rendering of Fields,Items and even WebParts using a JavaScript File (referenced in JS Link property field of a WebPart).

JSLink is one of the many cool features introduced by Microsoft in SharePoint 2013. It is a property that is available on many SharePoint objects like content types, lists, views, fields and web part properties. We simply point this property to a JavaScript file that will do a magic on our page.

These results demonstrate the confusion surrounding JSLink and CSR quite nicely. The first two talk about it being an approach to customizing the rendering of views, forms, fields, and/or web parts, but this is actually CSR, not JSLink. Now the authors understand the difference I’m sure, but these synopsis’ can at a bare minimum be interpreted as if they are the same.
 
The third result is actually correct (not that surprising since it is a TechNet article). Then again, the fourth hit is also from TechNet, and implies that the two terms are interchangeable, which again is not correct:

Set the JSLink property of your Web Part. Client-side rendering or JSLink is a new concept in SharePoint 2013.

They are in fact both new concepts in 2013, but they are not a single concept. The point is, JSLink is just a property, which can be set on various object instances in SharePoint, whose value specifies one or more JavaScript files that SharePoint should load whenever that object instance is loaded on the page, allowing the JavaScript to perform some kind of magic. That magic might be to override one or more CSR display templates, but it could just as easily have nothing to do with CSR whatsoever. By object instances, I mean instances of fields, views, content types, and web parts.
 
It does get a little tricky sometimes, because it doesn’t always work the way you might expect. For instance, if you set a JSLink property on a site column, the JavaScript will get loaded on any form or view which displays that column, whether the column was added to the list before or after the JSLink property was set. This is not the case with JSLink set on a site content type. If the content type was added to a list before the JSLink was set, the list will not load the JavaScript on forms after JSLink is set for the site content type. This is because when you add a content type to a list, it actually makes a copy of the content type for the list, instead of adding it as a reference like it does for site columns. Also, JSLink for content types is only loaded on forms, never for views. I assume this is because a view may display multiple content types, which could get messy in a hurry.
 
Anyway, many articles on JSLink only show how to set it on web parts, because this is easy, and you can do it through the browser. For the same reasons, this article will do the same, but very quickly (like my next post) I’ll talk about how to set it programmatically for other types of objects.

CSR Display Template Overrides for Forms

First, the API for applying display templates to SharePoint forms is encapsulated in a class called SPClientTemplates, which is loaded in the JavaScript file clienttemplates.js. You override the display templates for parts of the page by calling RegisterTemplateOverrides like so, and passing it an object that tells it what display templates you want to override.

Now the magic happens in what is defined in the overrides object that you pass into the function. This object has a structure that looks like:

Most of the magic happens in Templates.Fields, which is basically a hash map with a key equal to the internal name of the field, and a value that is an object describing what parts of the rendering I want to take over for that field. The comments above are replaced with either a string or a function that returns a string, and that string should contain the HTML that you want displayed for the given form.
 
There are a couple of things that you need to understand. First, if the string returned is an empty string (or null, or undefined, i.e. resolves to false in JavaScript), the SPClientTemplates will revert to the default rendering, so you can’t just hide a field by returning nothing (not to mention, you render the field, but you have no control over the label). Also, SPClientTemplates won’t allow your rendering method to crash the form; it traps all exceptions and reverts to the default rendering on exception (* this behavior has changed recently on SharePoint Online, if your CSR thows an exception there nothing is rendered for the field control, which is actually better because it makes it more obvious that your code crashed).
 
The other overrides, OnPreRender and OnPostRender, are not associated with any particular field. They get called back once for each field in the form, right before and right after the field is rendered respectively. And they’ll probably be called several more times than you expect. That’s because created, created by, modified, and modified by are also fields, and you can override their rendering as well.
 
Anyway, that’s enough theory for now, let’s start looking at an example.

Spying on Microsoft’s CSR

This is the only concrete example that will appear in this post, and it’s pretty trivial, but still useful for developers. It allows you to inject a function that will ultimately override rendering for a field, but then pass through the rendering to the default rendering. This allows you to easily set a break point in the debugger and step into the function that Microsoft uses to render a particular field type. Since the documentation for CSR has always been a little sketchy, sometimes this is the only way you can figure out what’s really going on.
 
However, in order for this to be useful, you need to get SharePoint to load the debug versions of it’s JavaScript files. To do that, modify the ScriptManager element of your master page and set ScriptMode to Debug like so:

Now let’s look at a the skeleton for our CSRSpy display template implentation:

This JavaScript has a single function named spy. Then it creates an override instance that effectively says use spy for rendering the Title field on the new, edit, and display forms. Finally, it calls RegisterTemplateOverrides passing the override object.
 
Now, for bonus points, if I deploy this as is, what gets rendered for the title field on say the new form. If you said a textbox just like normal, you get the bonus points. Why, because SPClientTemplates is going to call spy() to do the rendering, which returns nothing, which is the same as returning undefined, which evaluates to false in JavaScript, so SPClientTemplates falls back to the default rendering.
 
So let’s go ahead and implement the spy() method:

That first line looks pretty scary, but it’s just returning a map of field types to rendering methods. Don’t ask me how I figured that out, because I didn’t, I read it in a Code Plex article by Andrei Markeev (which I’ll include in references at the end). The ctx is a context that is passed into us by SPClientTemplates. It has a lot of stuff in it, which changes in different callbacks. We use it to get the current field type, from which we get the current rendering templates. Then we use the current base view id to get the actual rendering method for the current form. Finally, we call that method and return the result.
 
Again, the title is going to actually be rendered by the default rendering, so it’s going to be a textbox just like we’re used to. But if I get this JavaScript loaded, I can now set a break point on currentRenderFunc(ctx), and step into the default rendering to see how SPClientTemplates gets it done.
 
To get it installed on the new form of a list, go to the new form and edit it. Then edit the form web part. Set the JSLink in the Miscellaneous section to the full path to the CSRSpy.js file (which must be in the same site collection as the list, I set mine to ~sitecollection/Style Library/CSRSpy.js, so yes you can use ~sitecollection or ~site).

Set CSR as JSLink on Web Part

Now save the form and reload it, launch the debugger, open CSRSpy.js in the debugger, and put a break point on the line that calls the default rendering. Reload the page and step into the default rendering. It will take you into to the method SPFieldText_Edit in clienttemplates.js, which seems to make sense because title is of type SPFieldText.
 
Here is a screenshot of SPFieldText_Edit in the debugger:

SPFieldEdit_Text

About half of the code is constructing the HTML that will be returned by the method to be rendered, but there is a lot more going on here. In particular, the render context is converted to a form context, and that is used to register callbacks for various form events.
 
Also, one of the confusing things about Client-side Rendering is that a lot of times you don’t seem to have much context to work with. For instance, in these register callback methods, the function that gets called back gets no arguments passed in, and you find yourself scratching your head saying what do I do now, I don’t even know what field I’m getting called back for. There are two approaches you can take to overcome this.
 
You can use the JavaScript method bind to “pass” additional arguments to your callback like the render context, as Martin Hatch does (link below). Bind is called on a function, and produces a new function, on which you can hard code some additional parameters (and the this pointer). Bind is confusing to a lot of people, but no more so than the other approach used by Microsoft’s client templates and mine.
 
And that alternative is that you can form a closure. A closure is just a function that is created within another function, but somehow exposed outside the function (like through passing it as a callback for an event or returning it). When called, the function’s outer state is restored to what it was when the function was created.
 
Ok, that was clear as mud, but it’s not that hard. Let’s try an example. SPFieldText_Edit creates a function called InitControl, which it registers as a init callback. When it gets called back, the render context (rCtx) gets restored to what it was when InitControl was created. So if SPFieldText_Edit is called 3 times for 3 different fields, 3 different InitContol methods are created and registered as init callbacks, and when they are called they each get they’re own rCtx restored to what it was for the field for which they were created.
 
Anyway, here are what I think are the interesting parts of SPFieldText_Edit:
 
  • SPClientTemplates.Utility.GetFormContextFormCurrentField
  • formCtx.registerInitCallback
  • formCtx.registerFocusCallback
  • formCtx.registerGetValueCallback
  • formCtx.registerHasValueChangedCallback
The first is how we get the form context from the render context that we are passed, and then there are four form events that we can register callbacks for by calling the appropriate register method of the form context. Here is a brief description of each of the register callback events listed above.

There are several more callbacks you can register for, mostly related to validation, which I’ll cover in a later post.

Wrap

I found some very good blog posts about CSR, which I will share below, but the Microsoft documentation is…not great, and as good these posts were I still found myself learning much the hard way. The hard way was a lot of trial and error, and some stepping through the client templates from Microsoft using the spy template above. So even though this isn’t exactly a new topic I figured I’d write-up what I’ve found in the hopes that it is useful to someone.
 
In my next post I’ll give a more real example of a simple CSR template implementation and show how to deploy it by setting the JSLink property on a site column programmatically using JSOM.

References

CSRSpy.zip – the source code for this post.

Leave a Reply

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

Scroll to top