Latest Posts

SharePoint Client-Side Rendering (CSR) in List View

When we add list view web part on a page, it comes in the tabular format. In real-time scenarios, we don’t always want data to be presented that way. CSR – Client-Side Rendering is a feature in SharePoint using which you can render the data easily with the help of a few overriding methods given in SharePoint APIs.

What is Client-Side Rendering - CSR?

  • CSR is a feature in SharePoint that helps us to modify the rendering of the list view data on the SharePoint page.
  • As the name suggests, CSR works on client-side so whatever calculation/modification we do using CSR code, that is on the client-side only and there’s no impact on the server because of CSR coding, A big advantage!
  • You load data using list view web part on your page and then using CSR you can modify the presentation of the data in a way you like.
  • CSR is used in (1) list view, (2) list form and (3) search templates. In this article, we are going to learn the list view customization using CSR.

Objects that can be customized using CSR

Called multiple times in page load sequence

  1. Field
  2. Item
  3. Group

Called only one time in the page load sequence

  1. Header
  2. Footer
  3. View
  4. Body

Additional events for customization

  1. Onprerender
  2. OnPostRender

Main API to use CSR is:

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(options)

Client-side rendering (CSR) All in one code sample

List Created for the example - CSRList

Columns of the list.

Column DataType

Outlook

Text

Temperature

Number

Humidity

Number

DisplayImage

Image

Description

Multiline

4 easy steps to implement CSR on your SharePoint Site

  1. Create a SharePoint List and add columns to the list
  2. Create a Web part page and add list view web part to the page.
  3. Create a JavaScript file and add a reference to the web part page using Script Editor Web part or JSLInk Property of the ListView Web part.
  4. Now, open the JavaScript file and put the code into it. I have mentioned all the CSR methods in this example. You need to modify the code according to your requirement.

NOTE:

Make sure that the columns you are using in CSR scripts are present in the list view web part that you are putting on the page otherwise you will see undefined written in the list view.

  • // Function to handle custom client-side rendering on pages
  • (function () {
  •     // Initialize the variable that stores the objects.
  •     var overrideCtx = {};
  •     overrideCtx.Templates = {};
  •  
  •     // Assign a function to handle the Pre-Render events
  •     overrideCtx.OnPreRender = preRenderHandler;
  •  
  •     // View
  •     overrideCtx.Templates.View = viewControl;
  •  
  •     // Body
  •     overrideCtx.Templates.Body = bodyControl;
  •  
  •     // Header
  •     overrideCtx.Templates.Header = headerControl;
  •  
  •     // Footer
  •     overrideCtx.Templates.Footer = footerControl;
  •  
  •     // Group
  •     overrideCtx.Templates.Group = GroupControl;
  •  
  •     // Item
  •     overrideCtx.Templates.Item = customItem;
  •  
  •     //Field
  •     overrideCtx.Templates.Fields = {
  •         "Temparature": { "View": TemparatureFieldcustomization },
  •         "Humidity": { "View": HumidityFieldcustomization }
  •     };
  •  
  •     // Assign a function to handle the Post-Render events
  •     overrideCtx.OnPostRender = postRenderHandler;
  •  
  •     // Set the template to the:
  •     // Custom list definition ID
  •     // Base view ID
  •     overrideCtx.BaseViewID = 1;
  •     overrideCtx.ListTemplateType = 100;
  •  
  •     // Register the template overrides.
  •     SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
  •  
  •     function TemparatureFieldcustomization(ctx) {
  •         var temp = ctx.CurrentItem.Temparature;
  •         var returnhtml = '';
  •         if (temp >= 80) {
  •             returnhtml += "<div style='color: white;background-color: red;text-align: center;font-weight: bold;'>" + temp + "</div>";
  •         }
  •         else {
  •             returnhtml += "<div style='color: white;background-color: green;text-align: center;font-weight: bold;'>" + temp + "</div>";
  •         }
  •         return returnhtml;
  •     }
  •  
  •     function HumidityFieldcustomization(ctx) {
  •         var humid = ctx.CurrentItem.Humidity;
  •         var returnhtml = '';
  •         if (humid < 57) {
  •             returnhtml += "<div style='color: black;background-color: aquamarine;text-align: center;font-weight: bold;'>Awesome!!</div>";
  •         }
  •         else if (humid >= 57) {
  •             returnhtml += "<div style='color: white;background-color: cadetblue;text-align: center;font-weight: bold;'>Boring</div>";
  •         }
  •         return returnhtml;
  •     }
  •  
  •     function customItem(ctx) {
  •         var ItemHTML = "";
  •         ItemHTML += "<div style='width:600px;height:150px;'><div style='float:left;width:170px'><img style='width:150px;height:125px;' src='" + ctx.CurrentItem["DisplayImage"] + "' /></div><div style='float:right;display: contents;'><span><strong>OUTLOOK: </strong>" + ctx.CurrentItem["Outlook"] + "</span><br /><span><strong>TEMPARATURE: </strong>" + ctx.CurrentItem["Temparature"] + "</span><br /><span><strong>HUMIDITY: </strong>" + ctx.CurrentItem["Humidity"] + "</span><br /><span>" + ctx.CurrentItem["Description"] + "</span></div></div>";
  •         return ItemHTML;
  •     }
  •  
  •     function bodyControl(ctx) {
  •         var htmlView = "";
  •         // If this rendering is repeating, you can check this filter and skip the rendering for the second time.
  •         // This filter will check the body and it will return the already loaded View. Try removing the condition.
  •         if (ctx.Templates.Body == '') {
  •             return RenderBodyTemplate(ctx);
  •         }
  •         var viewData = ctx.ListData;
  •         htmlView += "<table border='1'><tr><td><b> OUTLOOK </b></td><td><b> TEMPARATURE </b></td><td><b> HUMIDITY </b></td></tr>";
  •         for (var idx in viewData.Row) {
  •             var listItem = viewData.Row[idx];
  •             htmlView += "<tr><td>" + listItem.Outlook + "</td><td>" + listItem.Temparature + "</td><td>" + listItem.Humidity + "</td></tr>";
  •         }
  •         htmlView += "</table>";
  •         return htmlView;
  •     }
  •  
  •     function viewControl(ctx) {
  •         var htmlView = "";
  •         // If this rendering is repeating, you can check this filter and skip the rendering for the second time.
  •         // This filter will check the body and it will return the already loaded View. Try removing the condition.
  •         if (ctx.Templates.Body == '') {
  •             return RenderViewTemplate(ctx);
  •         }
  •         var viewData = ctx.ListData;
  •         htmlView += "<table border='1'><tr><td><b> OUTLOOK </b></td><td><b> TEMPARATURE </b></td><td><b> HUMIDITY </b></td></tr>";
  •         for (var idx in viewData.Row) {
  •             var listItem = viewData.Row[idx];
  •             htmlView += "<tr><td>" + listItem.Outlook + "</td><td>" + listItem.Temparature + "</td><td>" + listItem.Humidity + "</td></tr>";
  •         }
  •         htmlView += "</table>";
  •  
  •         return htmlView;
  •     }
  •  
  •     function headerControl(ctx) {
  •         return "<div style='font-weight:900;'>Weather Forecast</div><br />";
  •     }
  •  
  •     // Function to override the pagination control
  •     function footerControl(ctx) {
  •         return "<div style='font-weight:900;'>Replace OOB Paging Control</div>";
  •     }
  •  
  •     // Function to override group details
  •     function GroupControl(ctx, group, groupId, listItem, listSchema, level, expand) {
  •         var GroupHeading = '<div style="font-weight:bold"><span style="color:#777;">' + group + ' : <span><span style="color:#444;">' + listItem[group] + ' </span><span style="font-weight: lighter; display: inline-block;"> (' + listItem["Outlook.COUNT.group"] + ')</span></div><hr /><br />';
  •         return GroupHeading;
  •     }
  •  
  •     function fieldsControl(ctx) {
  •         var GroupHeading = '<div style="font-weight:bold"><span style="color:#777;">' + group + ' : <span><span style="color:#444;">' + listItem[group] + ' </span><span style="font-weight: lighter; display: inline-block;"> (' + listItem["Outlook.COUNT.group"] + ')</span></div><hr /><br />';
  •         return GroupHeading;
  •     }
  •  
  •     // Function to attend the OnPreRender event
  •     function preRenderHandler() {
  •         console.log('CSR Pre-render event');
  •     }
  •  
  •     // Function to attend the OnPostRender event
  •     function postRenderHandler() {
  •         console.log('CSR Post-render event');
  •     }
  • })();

CSR API explanation of each method

(1) Item - overrideCtx.Templates.Item

  1. This is the most important method and probably the most used method when comes to CSR.
  2. This method is called once for each row item as shown in the picture. So, if there are 5 rows in the list view web part, this method will get called 5 times.
  3. CSR-Item

Before implementing the CustomItem method, the list view web part on the page. Before Item CSR

After customitem method implemented, it looks like this. After Item CSR

(2) Group - overrideCtx.Templates.Group

This method is used when you have grouped by the list view results and you want to perform customization on the entire group as shown in the screenshot.

CSR-Group

Note:

  • If you have customized group and you want to see the items as well, make sure you keep the groupings Expanded as shown below from Edit View – Group By Section.
  • Once you customize group by, you might have to customize View - expand/collapse logic as well.
List view groupby expanded collapsed

Before applying the Group method, list view web part looks like below. In the view, I have grouped by Outlook field Before group CSR

After Group customization is implemented, it looks like this. I have also customized items in the same. After group CSR

(3) Fields - overrideCtx.Templates.Fields

You can use this method when you want to customize the field rendering in the list view web part. CSR-Field

  • For each field, you can customize –
    • Field view in list view web part
    • Field view in Edit Form
    • Field view in Display Form
    • Field view in New Form

    In this tutorial, we will see how to customize the rendering in the list view web part

  • Understand the syntax – you need to define different function/HTML string for each field and for each form (View/Edit/Display/New).
  • Fields: {
  •     'Field1 Internal Name': {
  •         View: /* function or string */,
  •             EditForm: /* function or string */,
  •         DisplayForm: /* function or string */,
  •             NewForm: /* function or string */
  •     },
  •     'Field2 Internal Name': {
  •         View: /* function or string */,
  •             EditForm: /* function or string */,
  •         DisplayForm: /* function or string */,
  •             NewForm: /* function or string */
  •     }
  • }

NOTE:

While applying customization for Fields and Item at the same time, Fields customization will not work. You remove Item customization and Field customization will start working. I didn’t find any proof of the same that both simultaneously don’t work but if you think logically, you don’t even require that.

Before applying Fields customization, the list view web part looks like below. Considering two number fields for example so it will be easy to understand.

Before field CSR

After Field customization is implemented, it looks like this. I have also customized items in the same. After field CSR

(4) Header - overrideCtx.Templates.Header

The Header part of the list view web part is handled using this method.

CSR-Header

As shown in the screenshot, if you want to customize the header part then you can use this method.

(5) Footer - overrideCtx.Templates.Footer

The Footer part of the list view web part is handled using this method.

CSR-Footer

(6) View - overrideCtx.Templates.View

If you want to rewrite the complete view then you can use this method. Remember, Paging control is separate and it is part of Footer control it is not included in View overriding.

CSR-View

Note:

Header control is part of the view render so if you are overriding View then, you won’t be able to override Header separately though you can override Footer separately.

Here, I have written all the data in tabular format.

after view CSR

(7) Body - overrideCtx.Templates.Body

Here, you can override the entire body except for Header and Footer. All the results/rows elements will be part of the Body control overriding.

CSR-View

Here, you can notice you can customize only the Body of the list view web part. Header and Footer are separately customized.

After Body CSR

(8) OnPreRender - overrideCtx.OnPreRender

This event fire before the DOM is loaded. Generally, we use this method to call any other methods, the results of which, we can use in other overriding methods.

(9) OnPostRender - overrideCtx.OnPostRender

This event fire after the DOM is loaded. This is very essential method when you want to manipulate something which is loaded on DOM.

Target specific list view in client-side rendering

In case you have multiple list view web part on the page and you want to target one view for your CSR, you have three options

  1. BaseViewID – You can find out this value from page source where you have your list view. Right-click on the page >> click on view page source >> Search BaseViewID in page source. You will get the number.
  2. ListTemplateType - What if we have two web parts with the same BaseViewID? ListTemplateType might be the answer. You can check the complete list of List Template Types.
  3. What if both BaseViewID and ListTemplateType are same? You can apply one easy approach mentioned below. In your CustomItem method, you can track it based on content type.
  • if (ctx.CurrentItem.ContentType == 'ContenType A') {
  •     return RenderMethodA(ctx);
  • }
  • else if (ctx.CurrentItem.ContentType == 'ContentType B') {
  •     return RenderMethodB(ctx);
  • }

Conclusion

We covered every aspect of Client-side rendering, right from understanding CSR, advantages of it, all the different CSR APIs and implementation of all the methods.


We value your Feedback:

Page URL:

Name:

Email:


Suggestion:

© 2024 Code SharePoint