SharePoint JSLink: Multiple web parts on a page

With JSLink you have the ability to quickly and easily change how a list views and forms are rendered. Together with jQuery, CSS and even JavaScript you can present a SharePoint list in endless ways. JSLink works very well when you only one web part with a custom JSLink located on a page. The default behavior with multiple web parts on a page is that all web parts will use the JSLink. This is counter intuitive since we set the JSLink on one web part. With the solution below we can make sure that only the correct web part use the custom JSLink code. The solution is created in cooperation with Peter van Koesveld.

Solution

This solution works for a page where one web part needs to be modified by the JSLink.

  1. Create a JavaScript file with the following code: JSLinkMultipleWebParts.
  2. Change the if statements to match the name of the list.
    if (ctx.ListTitle == "ListTitle")
    
  3. Change the headerHtml, ItemHtml and footerHtml to show the list as required.
  4. In the example the Title field will be displayed, make sure this field is available.
  5. Save the JavaScript file to SharePoint.
  6. Set the JSLink property.

Explanation

  1. The JSLink overrides the default Templates (Header, Item and Footer).
  2. Then if the ListTitle equals the provided ListTitle the custom code is run for the header, Item and Footer.
  3. If the ListTitle does not match the default RenderTemplate will be used.
    function renderItem() {
        if (ctx.ListTitle == "ListTitle") {
            //CustomItemRender
        } else {
            //Return the default Item Template
        	return RenderItemTemplate(ctx);
        }
    }
    
    • RenderHeaderTemplate
      return RenderHeaderTemplate(ctx);
      
    • RenderItemTemplate
      return RenderItemTemplate(ctx);
      
    • RenderFooterTemplate
      return RenderFooterTemplate(ctx);
      
Share

4 Replies to “SharePoint JSLink: Multiple web parts on a page”

  1. Thanks for this post. It helped me a lot but wasn’t quite what I needed because I had multiple web parts showing different views of the same list on the same page. I was able to adapt the code and leverage JQuery to look for web part title rather than list title. Sharing this trick here in case others stumble across your post and have the same issue I did!

    var webPartSpanID = "#WebPartTitle"+ctx.wpq;
    var webPartTitle = $(webPartSpanID).attr("title");
    if (webPartTitle == "ENTER WEB PART TITLE HERE")

  2. Why do you need override templates if you even do not know if it is your lpvp? To verify it on each stage (header, item, footer)?

    You should check it as soon as possible and name functions with naming convention kind of YournameRenderItem…

    pupils =)

Leave a Reply to Stanley Rozen Cancel reply

Your email address will not be published. Required fields are marked *