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);
      

SharePoint JSLink: Accordion

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. In this example I will create a FAQ list with a accordion display style.

Solution

  1. Create a custom list called FAQ with a title and description field (Multiple Lines of Text).
  2. If required changed the fields to be shown.
  3. Create a page and add the FAQ web part to the page.
  4. Create the JSLink file called AccordionView.js
  5. Create the JavaScript file called accordion.js
  6. Create the CSS file called accordion.css
  7. Save the background image to SharePoint.
  8. Change the background-image URLs if needed.
  9. Link the JSLink to the web part to load the AccordionView.js.
  10. Add the accordion.js and accordion.css to the page, for example by using a Content Editor web part.
  11. Add jQuery to the page.
  12. Make sure that jQuery is loaded before the other JavaScript. Errors might otherwise be generated.