This post has been migrated from www.experimentsincode.com, we apologise if some of the images or content is missing
This post has been migrated, original date 18 Oct 2008
After my post
Sitecore Sublayout Parameters I had a question about how to get the ID of the current sublayout without having to hard code the ID. So here is the code:
15 public partial class layouts_MySubLayout : System.Web.UI.UserControl
16 {
17   private readonly string _layoutSearch = "/sitecore/layout/sublayouts//*/{0}";
18   protected void Page_Load(object sender, EventArgs e)
19   {
20     string className = this.GetType().Name;
21
22     //for this is example I am using a Web Site project.
23     //This means that when I create any User Control it prefixes with 'layouts_' (directory name)
24     //and suffixes '_ascx' (file extension) to the compiled class name. These have to be removed
25     className = className.Replace("_ascx","");
26     className = className.Replace("layouts_", "");
27
28     Response.Write(string.Format(_layoutSearch, className));
29
30     Sitecore.Data.Items.Item template = Sitecore.Context.Database.SelectSingleItem(
31       string.Format(_layoutSearch, className)
32     );
33
34     if (template != null)
35     {
36       Response.Write(template.ID);
37     }
38     else
39       Response.Write("Not Found");
40
41   }
42 }
Couple of things to note:
- When using a Web Site project you will notice that it prefixes and suffixes extra text to the end of your class name at compile time, this has to be removed.
- I have also assumed that you have kept the name of the class the same as the name of the template.
- If you are not using a Web Site project but instead using a Web Applicatiton project you maybe able to remove line 25 and 26; just be sure to remove any namespaces so that you are only left with the class name.
- The code must be run in a member of the sublayout you are trying to retrieve the ID for otherwise you will get an class name