Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sitecore access layout definition programmatically

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
like image 543
Moo Avatar asked Dec 31 '15 00:12

Moo


1 Answers

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);
like image 141
RvanDalen Avatar answered Nov 05 '22 15:11

RvanDalen