Programmatically access Sitecore item presentation

During regular use, we usually access the presentation of an item through sitecore, but at times, you might need to be able to do this through your back end code.

In our scenario, we had various frame sublayouts which we used throughout the site to maintain page structure.
The front end required a certain class to be added to the top level body tag which resided in the layout file, only when a certain frame sublayout was in use.

Not wanting to achieve this through javascript since this was a fairly large dependency – front end wise, we decided to examine the presentation of the context item programmatically to determine if the given frame sublayout was a part of it. (Using the __Renderings field we could access the presentation of a given item) This code was executed in the layout file.
Mind you, this code is only meant for the default first device in presentation.

The following method can be used to determine if a given sublayout is a part of the presentation of the ‘currentItem‘ passed into the method.

        public class LayoutHelper
        {
            /// <summary>
            /// Checks if any of the sublayouts specified in 'sublayoutGuids' is present in the presentation of the 'currentItem'
            /// </summary>
            /// <param name="currentItem">The current item.</param>
            /// <param name="sublayoutGuids">The sublayout guids.</param>
            /// <returns>true / false</returns>
            public static bool AnySublayoutInPresentation(Item currentItem, List<string> sublayoutGuids)
            {
                var layout = LayoutDefinition.Parse(LayoutField.GetFieldValue(currentItem.Fields["__Renderings"]));

                if (layout.Devices != null && layout.Devices.Count > 0)
                {
                    var dev = (DeviceDefinition)layout.Devices[0];
                    if (dev != null)
                    {
                        var renderings = dev.Renderings;
                        if (renderings != null)
                        {
                            if (renderings.Cast<RenderingDefinition>().Any(rend => sublayoutGuids.Contains(rend.ItemID)))
                            {
                                return true;
                            }
                        }
                    }
                }
                return false;
            }
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s