Using this code I managed to change the renderings on the current item. However this changed it permenantly in Sitecore (the changes were could be seen in the CMS) and not temporarily, as I expected.
void ReplaceLayout(Item item)
{
if (item == null)
return;
using (new SecurityDisabler())
{
// New item
LayoutField newLayoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);
LayoutDefinition newLayoutDefinition = LayoutDefinition.Parse(newLayoutField.Value);
DeviceDefinition newDeviceDefinition = newLayoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());
// Current item
LayoutField layoutField = new LayoutField(Sitecore.Context.Item.Fields[Sitecore.FieldIDs.LayoutField]);
LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());
deviceDefinition.Layout = newDeviceDefinition.Layout;
deviceDefinition.Renderings = newDeviceDefinition.Renderings;
Sitecore.Context.Item.Editing.BeginEdit();
layoutField.Value = layoutDefinition.ToXml();
Sitecore.Context.Item.Editing.EndEdit();
}
}
I don't want to make permenant changes to the item, I just want to replace the currently displayed items renderings on the fly if some conditions are met. Does anyone know how to alter an item's layout in this way?