Hiding SharePoint 2010 web templates programmatically

When you allow your users to create sites with SharePoint 2010 – they have variety of web templates to chose from; you may choose to show only templates you’re comfortable being used on your site.

In my book we looked at how you can limit the templates used in the web declaratively when creating new site template. Let’s take a look how you can limit allowed web templates on any site once it’s already created.

1. Create new SharePoint 2010 project in Visual Studio
2. Add a new feature and a receiver to it.
3. Add the following code to the body of the receiver’s FeatureActivated method

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb web = properties.Feature.Parent as SPWeb;
SPWebTemplateCollection existingWebTemps = web.GetAvailableWebTemplates(1033); ;
Collection<SPWebTemplate> newWebTemps = new Collection<SPWebTemplate>();
for (int i = 0; i < existingWebTemps.Count; i++)
{
if (!existingWebTemps[i].Title.ToLower().Contains("blog"))
{
newWebTemps.Add(existingWebTemps[i]);
}
}
web.SetAvailableWebTemplates(newWebTemps, 1033);
web.Update();
}

Above, we get a hold of the collection of existing templates and then remove the ones that have “blog” in a title to create a new collection. Notice how you can set the separate collection of allowed web templates for different language locales.

Now, deploy the code and activate the feature; blog web template will be removed from the list of available template. Modify the logic to see how you can remove other templates.

To reset all templates to show up use: web.AllowAllWebTemplates() in your code.

Give it a try!

This entry was posted in sharepoint, sharepoint 2010 and tagged , . Bookmark the permalink.

Comments are closed.