Client-Side Rendering : Fields

I realize that there are several posts out there regarding this topic but it’s something that I’ve been wanting to play with for a while and I had nothing to do this weekend.

Client-side rendering is simply the process of using JavaScript to manipulate how certain data is rendered.  In this post, I’ll explain a simple JavaScript file that I threw together that checks the value of a specific field and displays an image in place of it’s text.

I have a custom list with a column called Gender.  Gender is a choice field with two possible options: “Male” or “Female”.  The example below starts by defining which field we want to manipulate.  The line containing genderContext.Templates.Fields is where we specify which column will be manipulated.  When I created the Gender column, SharePoint gave it an internal name of “y34x” so that’s how I’m identifying which column we’re dealing with.  Next you specify what needs to be manipulated.  In this case, I want to update the view and I’m passing in the name of the function that will do the work.  You can also update the forms if you choose to.

(function () {
var genderContext = {};
    
genderContext.Templates = {};
genderContext.Templates.Fields = {
  "y34x": {
    "View": GenderViewTemplate
    //DisplayForm: 
    //EditForm:
    //NewForm:
   }
};

SPClientTemplates.TemplateManager.RegisterTemplateOverrides( genderContext );
})();

This next section is the function that changes the rendering.  As you can see, we start by getting the value of the field that we’re interested in.  In this case, we’re passing that value to a variable called gender.  Next, we define what we want to return in place of that value.  As you can see, we’re returning an image tag.

function GenderViewTemplate( ctx ) {
  var gender = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
  var returnValue = '';

  switch ( gender ) {
    case "Male":
      returnValue = "<img src='/_layouts/15/images/ClientSideRendering/business_user.png' style='height: 32px; width: 32px' />";
    break;
    case "Female":
      returnValue = "<img src='/_layouts/15/images/ClientSideRendering/female_business_user.png' style='height: 32px; width: 32px;' />";
    break;
  }
 
  return returnValue;
}

I published the JavaScript file and images to the file system and now need to reference the JavaScript file where I want to use it.  Edit the list view web part and expand the miscellaneous section.  At the bottom, you’ll see a JS Link textbox where you can specify the path to your js file.


Click OK and your list will look like the following.
Advertisements