Jon*_*Jon 1 .net c# sitecore sitecore6
使用此代码,我设法更改当前项目的渲染.然而,这在Sitecore中永久性地改变了(变化可以在CMS中看到),而不是像我预期的那样暂时改变.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我不想对项目进行永久性更改,我只想在满足某些条件的情况下动态替换当前显示的项目渲染.有谁知道如何以这种方式改变项目的布局?
您在评论中解释说,您希望在侧栏中显示某些子布局,具体取决于某些表单部件/步骤.您可以通过添加适合子布局的PlaceHolder(例如在侧边栏中)并使用此代码动态渲染子布局来实现.
首先,您需要一个项目(我称之为片段项目),该项目在其演示设置上配置了子布局.然后,您可以使用代码在占位符(phSideBarPlaceHolder)中呈现该项目.
// Load snippet item
Item snippet = Sitecore.Context.Database.GetItem("{id-or-path-of-snippet-item}");
// Get the first rendering from item's presentation definition
RenderingReference rendering = snippet.Visualization.GetRenderings(Sitecore.Context.Device, false).FirstOrDefault();
// We assume that its a Sublayout, but you can also check for xslt and create an XslFile() object
Sublayout sublayout = new Sublayout();
sublayout.DataSource = snippet.Paths.FullPath; // creates a reference to the snippet item, so you can pull data from that later on
sublayout.Path = rendering.RenderingItem.InnerItem["Path"];
sublayout.Cacheable = rendering.RenderingItem.Caching.Cacheable;
// Copy cache settings
if (rendering.RenderingItem.Caching.Cacheable)
{
sublayout.VaryByData = rendering.RenderingItem.Caching.VaryByData;
sublayout.VaryByDevice = rendering.RenderingItem.Caching.VaryByDevice;
sublayout.VaryByLogin = rendering.RenderingItem.Caching.VaryByLogin;
sublayout.VaryByParm = rendering.RenderingItem.Caching.VaryByParm;
sublayout.VaryByQueryString = rendering.RenderingItem.Caching.VaryByQueryString;
sublayout.VaryByUser = rendering.RenderingItem.Caching.VaryByUser;
}
// Now render the sublayout to the placeholder
phSideBarPlaceHolder.Controls.Add(sublayout);
Run Code Online (Sandbox Code Playgroud)
如果您需要有关如何在子布局代码中读取DataSource属性的更多信息,Mark Ursino已经写了一篇文章:http://firebreaksice.com/using-the-datasource-field-with-sitecore-sublayouts
| 归档时间: |
|
| 查看次数: |
4983 次 |
| 最近记录: |