Sitecore access layout definition programmatically
Asked Answered
A

1

6

I want to access the layout definition of an item so that I can access the renderings added to the item, and then access the datasources attached to said renderings. I can't seem to find a way to do this. The best I could do is access the __renderings field but I then found out that this is going to access the original rendering definition item rather than the specific, datasourced instance stored in the Design Layout.

This is on Sitecore 7.5 MVC

If it helps, this is what I tried doing:

// Get the default device
DeviceRecords devices = item.Database.Resources.Devices;
DeviceItem defaultDevice = devices.GetAll().Where(d => d.Name.ToLower() == "default").First();

// Get the rendering references for the default device
Sitecore.Data.Fields.LayoutField layoutField = item.Fields["__renderings"];
Sitecore.Layouts.RenderingReference[] renderings = layoutField.GetReferences(defaultDevice);

// Get the required renderings
RenderingItem headerRenderingItem = null;
RenderingItem aboutRenderingItem = null;

foreach (var rendering in renderings)
{
    if (rendering.Placeholder == "headerPlaceholder")
        headerRenderingItem = rendering.RenderingItem;
    else if (rendering.Placeholder == "/aboutSectionPlaceholder/textPlaceholder")
        aboutRenderingItem = rendering.RenderingItem;
}
Assert.IsNotNull(headerRenderingItem, "no header rendering item found");
        Assert.IsNotNull(aboutRenderingItem, "no about rendering item found");

// Get their datasources
ID headerDatasourceId = ID.Parse(headerRenderingItem.DataSource); // The datasource string is null as it is accessing the datasource definition item itself
ID aboutDatasourceId  = ID.Parse(aboutRenderingItem.DataSource);  // Same as above
Agler answered 31/12, 2015 at 0:49 Comment(0)
T
6

The RenderingReference.RenderingItem refers to the rendering item in the /layout section. What you could do is use RenderingReference.Settings.Datasource.

So your code would look something like:

foreach (var rendering in renderings)
{
    if (rendering.Placeholder == "headerPlaceholder")
        headerRenderingDatasourceId = rendering.Settings.Datasource;
    else if (rendering.Placeholder == "/aboutSectionPlaceholder/textPlaceholder")
        aboutRenderingDatasourceId = rendering.Settings.Datasource;
}

Item headerRenderingDatasourceItem;
if (!string.IsNullOrEmpty(headerRenderingDatasourceId)
    headerRenderingDatasourceItem = item.Database.GetItem(headerRenderingDatasourceId);
Threefold answered 31/12, 2015 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.