How do you get the Sitecore Sublayout from a Usercontrol? A Sitecore Sublayout (Sitecore.Web.UI.WebControls.Sublayout) is a container for your Usercontrol (.ascx) page. Therefore the Sublayout is retrieved by typecasting the parent to a Sublayout:
using Sitecore.Web.UI.WebControls; Sublayout thisSublayout = (Parent as Sublayout);
Having the Sublayout in hand enables you to read the Sublayout data, for example the “datasource” field. The datasource field can be used to alter which item the Sublayout should render. You can apply a datasource to your sublayout directly, telling the userControl (.aspx page) to render a different item than the current item (Sitecore.Context.Item).
In one of my recent projects (for Sitecore Foundry, but the code works for Sitecore 5 and Sitecore 6 as well) I inherited from this base class instead of the System.Web.UI.UserControl. The class is very simple. It gives me the Sitecore item as stated in the datasource, or the current item if the datasource item is not set:
using Sitecore.Data.Items; using Sitecore.Web.UI.WebControls; namespace MyProject.MyNameSpace { /// <summary> /// This class contains the CurrentContextItem function /// which allows the system to use /// the datasource property on sublayouts. /// </summary> public class SublayoutBaseClass : System.Web.UI.UserControl { /// <summary> /// Gets the current context item. /// </summary> /// <value>The current context item.</value> protected Item CurrentContextItem { get { Sublayout thisSublayout = (Parent as Sublayout); if (thisSublayout == null) return Sitecore.Context.Item; if (string.IsNullOrEmpty(thisSublayout.DataSource)) return Sitecore.Context.Item; string dataSource = thisSublayout.DataSource; Item dataSourceItem = Sitecore.Context.Database.GetItem(dataSource) ?? Sitecore.Context.ContentDatabase.GetItem(dataSource); if (dataSourceItem == null) return Sitecore.Context.Item; return dataSourceItem; } } } }
This is very good, and it will be even better if you expose access to the attributes, particularly since they can be used in a user-friendly manner since 6.1 thanks to Rendering Parameter Templates.
LikeLike
We have found this very useful for development – how about adding set as well so that the datasource can be pushed to say in a repeater?
LikeLike
Thanks Brian! This seems like a much cleaner solution than using the SublayoutParameterHelper classes.
http://trac.sitecore.net/SublayoutParameterHelper
LikeLike
Hi. I noticed that Sitecore.Web.UI.WebControl has a protected GetItem() method that does this, but also support relative datasource paths (by calling Sitecore.Context.Item.Axes.GetItem(dataSource)). Too bad it’s not a public method, though you should be able to use reflection to call it…
LikeLike
Pingback: Sitecore find Unused Sublayouts | Brian Pedersen's Sitecore and .NET Blog