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.
- Create a JavaScript file with the following code: JSLinkMultipleWebParts.
- Change the if statements to match the name of the list.
if (ctx.ListTitle == "ListTitle")
- Change the headerHtml, ItemHtml and footerHtml to show the list as required.
- In the example the Title field will be displayed, make sure this field is available.
- Save the JavaScript file to SharePoint.
- Set the JSLink property.
Explanation
- The JSLink overrides the default Templates (Header, Item and Footer).
- Then if the ListTitle equals the provided ListTitle the custom code is run for the header, Item and Footer.
- 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);
- RenderHeaderTemplate
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")
Thanks, Karen. That’s what I needed!
Excellent!! Exactly what I was looking for
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 =)