MDS Enabled Sub-sites and Display Templates

Last year I released some of my templates for JSlink onto the SPCSR repository, but I was never totally happy with the solution for MDS (Minimal Download Strategy) enabled sites.

Basically, in order to make sure that MDS recognises our scripts and doesn’t remove them when it’s processing the page refresh, we had to use the RegisterModuleInit method, with the path to our script and then the method to call once loaded.

This looked like:-

RegisterModuleInit("/_catalogs/masterpage/Display%20Templates/csr_ovr_RenderFormManager.js", pfh.RegisterTemplateOverride);

//or for a sub-site

RegisterModuleInit("/Sites/HR/_catalogs/masterpage/Display%20Templates/csr_ovr_RenderFormManager.js", pfh.RegisterTemplateOverride);

This meant that to use the display templates in multiple site collections that had MDS enable, you had to create multiple copies of the template, address for each site collection.

Obviously that isn’t ideal, so when I was looking at this problem for my session at the Evolutions Conference in April, I realised that MDS enabled sites have a very predictable URL of :-

HTTPS://HOSTNAME/_LAYOUTS/15/START.aspx/

pfh.sitecolpath = window.location.pathname.substring(0,window.location.pathname.indexOf("/_layouts/15/start.aspx"))
RegisterModuleInit(pfh.sitecolpath + "/_catalogs/masterpage/Display%20Templates/csr_ovr_RenderFormManager.js", pfh.RegisterTemplateOverride);

In the event that we have a non MDS enable site, the RegisterModuleInit is ignored, so it doesn’t matter that the path is wrong.

I’ve tested this in IE and Chrome which both respond well, so I’ve updated the display templates in GitHub. (https://github.com/SPCSR)

Paul.

After I posted this, Elio Struyf sent me a quick tweet reminding me of the _spPageContextInfo object, and more specifically the .siteAbsoluteUrl property, which gives the absolute URL for the current site collection.

This is a much better way of doing it, so I shall adopt this method instead.

The code now reads:-

RegisterModuleInit(_spPageContextInfo.siteAbsoluteUrl + "/_catalogs/masterpage/Display%20Templates/csr_ovr_RenderFormManager.js", pfh.RegisterTemplateOverride);

 

Well unfortunately, the spPageContextInfo seems to have an issue.. it doesn’t always get populated before the Display Template registration is performed, so every now and again the object is null and your display template refuses to load. so I’m going to drop back to my first method of calculating the URL on the fly!

Leave a Reply

Your email address will not be published.

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.