15 December 2010

Getting an items rendering

Often you need to get the rendering(s) used to render a given item from a codebehind. You want to get the rendering, that the rendering engines uses. That means, that if there isn't a rendering on the item, you should look at the template and so forth.
I spent some time figuring out, how this is done (I actually ended up asking Sitecore Support), so I thought I would just share it with you:

/*First you need the item you want the renderings from. In this case lets use the current Item */
Sitecore.Data.Items.Item item = Sitecore.Context.Item;
/*We also need the device, so we get the renderings attached to that. */
Sitecore.Data.Items.DeviceItem device = Sitecore.Context.Device;

/*This is how you get the rendering */
Sitecore.Layouts.RenderingReference[] renderings = item.Visualization.GetRenderings(device, true);


This is actually pretty simple,which might be the reason for me not figuring it out. ;)
As you now have an array of RenderingReference, you can look up the rendering by its ID or whatever.

No comments:

Post a Comment