Rendering XSLT’s (or sublayouts for that matter) from another item can be very usefull. For example, if you have a spots region on your page, and each spot is rendered by different XSLT’s, you can place the XSLT rendering on each spot item (instead of placing them on the page itself) and the let a sublayout render the renderings for you.
First you need to get hold of the item containing the renderings to render. In this case I call the item “spot”.
Then you need to get the renderings from that item for a specific context. I use the current context.
At last you can iterate over each rendering and render them to the page.
To do all this you will need to override the CreateChildControls of the ascx rendering the renderings.
Also, you need a control to add the renderings to. I use a panel.
So, lets take it from the beginning. I create a .ascx page with a panel on it called panDynamicSpots:
<asp:Panel ID="panDynamicSpots" runat="server"> </asp:Panel>
Then I override the CreateChildControls of the .ascx to render my XSLT’s on the panDynamicSpots:
using Sitecore.Data.Items; using Sitecore.Layouts; using Sitecore.Web.UI.WebControls; protected override void CreateChildControls() { // Somewhere in my code I have got hold of the item // containing the renderings to render. The item is called "spot" Item spot = GetItemContainingSpotToRender(); // Fictive function // Then call the RenderSpot to render the XSLT's on the spot RenderXsltSpot(spot); base.CreateChildControls(); } private void RenderXsltSpot(Item spot) { // Loop through all renderings on the item foreach (RenderingReference rendering in spot.Visualization.GetRenderings(Sitecore.Context.Device, false)) { // Get the path to the XSLT string path = rendering.RenderingItem.InnerItem["Path"]; // Create an instance of a XslFile XslFile xslSpot = new XslFile(); xslSpot.Path = path; xslSpot.DataSource = spot.Paths.FullPath; // Add the XSL to the panel so it can be rendered panDynamicSpots.Controls.Add(xslSpot); } }
It is the function GetRenderings that returns me a list of all renderings on an item.
You could also extend the function to render sublayouts as well. You will need to find out which template the rendering is based on using the rendering.RenderingItem.InnerItem.TemplateName. Instead of instantiating a XslFile you would then instantiate a Sublayout().