Styling and Scripting SharePoint based on Web Template

Posted by & filed under , .

Often times when styling SharePoint you’ll come across some odd exception where the styling that works everywhere else has some weird side effect on a particular type of site, or you’ll want to limit some jQuery functionality to a specific site template. Here’s a neat little trick I came up with for splitting the styling and scripting of a particular template so it’s independent of the others.

Simple Version – Single Site Template

The key to this trick is in a built-in javascript variable called _spPageContextInfo.webTemplate which returns the numerical ID number correlating to the web template the current site is using.

In this example we’re checking to see if the value is 62, if it is, we know we’re in a Community Site, and so we add a class to the body, then we can start all of our Community-Site-specific CSS with .communitySiteBody and we know it won’t have an effect outside of Community Sites.

We can also stick in any custom code we need to in this block to get the functionality we’re after, without worrying about the code running on other types of sites.

Advanced Version – Specific Page In A Specific Site Template

We can even go a step further and target a single page within a certain type of site:

In this example, now we can have script that only runs on the Category.aspx page in a Community Site, and we’re able to target the CSS for this page exclusively by using the .communitySiteBody.categoryPageBody selector to start our CSS statements.

If you’ve ever had to write script or CSS around the way certain OOB web parts look or function on a specific page, you can appreciate how powerful this is. This will now let you change the styling of OOB web parts for a *specific page* in a *specific* type of site, without having to worry about side effects rippling through the rest of the site because you touched one of Microsoft’s overused classes.

Bonus – Add Classes For All Site Templates

The above is a great trick for writing scripts for specific web templates, but it gets tedious if you’re only doing it for the CSS tag. My recommendation is to use the above format to target specific sites for scripting purposes, and to continue using that method to create individual page CSS selectors as needed, but for the web template level CSS tagging, I recommend putting the below code into your core JavaScript somewhere.

This code will automatically label the body of every page with a class relating to the template being used. Implementing this at the start of your branding efforts should make it very easy to target specific types of sites, without messing up your previous efforts.

Thanks to Ryan McIntyre for providing a convenient list of Site Templates with IDs!

Leave a Reply