In his excellent post on How SharePoint 2007 Renders Its Content Geoff McElhanon shows how to programmatically load SharePoint-based templates. The code he shows us is as follows:

1
2
3
4
5
6
7
// Initialize template container with our custom template
templateContainer = new TemplateContainer();
templateContainer.Template = 
    SPControlTemplateManager.GetTemplateByName(RenderingTemplateId);
 
// Add the container to the webpart control hierarchy
Controls.Add(templateContainer);

However, I ran into a problem when I tried to load in a custom template of my own. The default location SharePoint searches in when you provide it with a template ID is C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES. My template was deployed in a subdirectory of this folder and although SharePoint is set to look in those as well, for some yet-to-be-defined reason it didn’t. So I needed an alternative. The solution is not rocket science but it did take me a while to figure it out:

1
2
3
4
5
6
7
8
// Initialize template container
templateContainer = new TemplateContainer();
Control ctl =
    (Control)Page.LoadControl( "~/_controltemplates/MyControlTemplates/MyControlTemplate.ascx" );
templateContainer.Template = ((RenderingTemplate)ctl.Controls[0]).Template;
 
// Add the container to the webpart control hierarchy
Controls.Add(templateContainer);

I hope this helps you out.

If you liked this post, please click on one of the advertisements below. Thanks!


1 Response to “Loading SharePoint templates from a different location”

  1. 1 Recent Faves Tagged With "alchemy" : MyNetFaves

Leave a Reply