-->

09/01/2013

JSLink - Custom JS Rendering in Sharepoint 2013

JSLink is the new feature introduced in SharePoint 2013, loading off the burden of XSLT webparts from developer's mind.
Lets me show you an example. I have two lists "Movies" and "Books".

But I want to display them on a page like  . . .
All this can be done just by using Java script and without creating a single webpart.
Lets see how to accomplish this task.

Step 1: 
Create an empty SharePoint project. Follow the steps mentioned in below image to create basic infrastructure.
Create all the required site columns. If you are not clear on this task, you can see Elements.xml file under "BookSiteColumns" from my sample code embedded below.

While creating content types, visual studio will display all the available fields (Existing in site + New ones you just created in this project). Select required fields to create the Content type.

once Content types are created, now create a list as shown below, and then you can associate the required content type.

Associating the newly created content types.

With this we created the required, Fields, Content Types and Lists.

Step 2:
Go to Movies List in VS2012 , and expand it.  First understand what we have here.
Elements.xml under MoviesInstance node will talk about the default data that can be populated in to movies list while deployment.
Elements.xml under Movies node will contain the definition of List like Name, template Type, Display name , etc.
Schema.xml under Movies node will have the detail of all the ContentTypes associated and Views available, and what fields will be displayed in each view.

Step 3:
By this time, you might have understood that we need to modify Schema.xml.
By default there will be couple Views available in schema file. Now I will create definition of a new View and add it in <Views></Views> section of schema.
      <View BaseViewID="2" Name="96E9EE4D-FCE6-44C3-A46B-434326DDAD6C" 
            DisplayName="CustomJSRendering" Type="HTML" 
            WebPartZoneID="Main" SetupPath="Pages\ViewPage.aspx" 
            Url="CustomJSRendering.aspx" DefaultView="TRUE">
        <ViewFields>                   
        <FieldRef Name="Movie"  DisplayName="Movie Name"/>
          <FieldRef Name="PopularityPercent" DisplayName="Popularity"/>        
        </ViewFields>
        <Query />
        <Toolbar Type="Standard" />
        <XslLink>main.xsl</XslLink>
        <JSLink Default="TRUE">CustomJSRendering1.js</JSLink>      </View>
Here we need to stress on a few important things. Url part of definition, you dint have any page with name "CustomJSRendering.aspx", but framework will take "Pages\ViewPage.aspx" page and mock it up with the definition and will render with name as "CustomJSRendering.aspx".

Step 4:
The definition says about the Name, ID, Url, Fields to be displayed. Now look at <JSLink> tag highlighted above. This says sharepoint that the way of rendering this View will be controlled by "CustomJSRedering1.js" file.
Now look at both the views of Movies list on top. I want to modify just the "PopularityPercent" field to display some colors based on the Values.
For that below is the JS content.
(function () {
    var overrideContext = {};
    overrideContext.BaseViewID = 2;
    overrideContext.ListTemplateType = 10001;
    overrideContext.Templates = {};
    overrideContext.Templates.Header = "<h2>My Custom Rendering Movies View</h2>";
    overrideContext.Templates.Fields = { 'PopularityPercent': { 'View': PopularityViewTemplate } };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
})();
function PopularityViewTemplate(ctx) { 
    var popularity = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
    var color = getColor(popularity);
    return "&nbsp;&nbsp;&nbsp;&nbsp;<span style='background-color : " + color + "' >&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;" + popularity + "%";
}
function getColor(pop) {
    if (parseInt(pop) > 70)
        return "Green";
    else if (parseInt(pop) > 40)
        return "Yellow";
    else if (parseInt(pop) > 20)
        return "Orange";
    else
        return "Red";
}
You can specify as <JSLink>~/Scripts/xxxxxx.js</JSLink> if you intend to deploy it in your VD. But sometimes sharepoint won't recognize the Script files. In that case you can simple mention as <JSLink>xxxxxx.js</JSLink> and deploy the script file to "15/Templates/Layouts".

OutPut:
Note: If you wish to see the AllItems View of this list, simply go to URL and change the CustomJSRendering.aspx to AllItems.aspx.


Step 5:
We have modified the rendering of a single field using <JSLink>. Now I want to modify complete View of Book List.
Again same steps, define a new View in Schema.xml file under Books List node.
      <View BaseViewID="2" Name="08B44EC8-7DC9-4C63-B43A-D867B869F625" 
            DisplayName="CustomJSRendering" Type="HTML" 
            WebPartZoneID="Main" SetupPath="Pages\ViewPage.aspx" 
            Url="CustomJSRendering.aspx" DefaultView="TRUE">
        <ViewFields>        
          <FieldRef Name="BookName" />
          <FieldRef Name="BookAuthor" />
          <FieldRef Name="AuthorCountry" />
        </ViewFields>
        <Query />
        <Toolbar Type="Standard" />
        <XslLink>main.xsl</XslLink>
        <JSLink Default="TRUE">CustomJSRendering.js</JSLink>        
      </View>
I will define how I want to render the view inside CustomJSRender.js file.
(function () {
    var overrideContext = {};
    overrideContext.BaseViewID = 2;
    overrideContext.ListTemplateType = 10000;
    overrideContext.Templates = {};
    overrideContext.Templates.Header = "<h2>My Custom Rendering Books View</h2>";
    overrideContext.Templates.Item = customItem;
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
})();
function customItem(ctx) {
    var ItemStyle = "display:inline-block;width:200px;height:120px;" +
        "border:2px black solid;background-color:#ffe;padding-top:20px;" +
        "padding-left:20px;color:black;text-align:center;font-size:12px";
    var ItemHTML = "<div style='" + ItemStyle + "'><h2>"
        + ctx.CurrentItem.BookName + "</h2>" +
        "<br/><br/><br/><em>" + ctx.CurrentItem.BookAuthor
        + "</em><br/><em><b>" + ctx.CurrentItem.AuthorCountry + "</b></em></div>";
    return ItemHTML;
}
Here is the output.

Step 6:
Now this is really an interesting part, when I want to display these lists on a Site Page, I just need to insert these Lists using Insert section in Edit mode of a Site page.
Once I insert both the Lists on Site page and save and view it in browse mode. The lists will be shown as we intended and designed, thanks to <JSLink>.

Sample Code :  Download "SP13CustomViewRendering.Zip" from my codebase library.

We have created a customized view for custom lists, with using new SharePoint 2013 feature <JSLink>.

Is it helpful for you? Kindly let me know your comments / Questions.

2 comments:

  1. Not exactly what I'm looking for right now, but all steps looks easy to understand and follow for get the results shown in the screenshots.

    PS: What I'm looking for is using CSR / JSLink is add in a View, a Column from other List based on a LookupId present in the actual View. (whitout using Visual Studio, only CSR). Sharepoint Online.

    ReplyDelete
  2. Where can I find more information on Context (ctx)? What is available to us via this call?

    ReplyDelete