How to get content of rendering programmatically?

社会主义新天地 提交于 2019-12-22 04:09:31

问题


I am attempting to write a method that will output the content (i.e. HTML) for any renderings that happen to exist within a specific placeholder. The goal is to pass in a Sitecore.Data.Items.Item and the placeholder key that i'm interested in, and the method should return the rendered content.

The issue with this seems to be that there is no page context established, and therefore calling RenderControl() is throwing a null reference error in the GetCacheKey() method of the Sublayout.

Is anyone aware of a way to render a Sublayout or XSLT rendering programmatically?

Here's what I've got so far:

private string GetPlaceholderContent(Item item, string placeHolder)
{
    StringWriter sw = new StringWriter();
    using (HtmlTextWriter writer = new HtmlTextWriter(sw))
    {
        foreach (RenderingReference renderingReference in item.Visualization.GetRenderings(Sitecore.Context.Device, false))
        {
            if (renderingReference.Placeholder == placeHolder)
            {
                // This ensures we're only dealing with Sublayouts
                if (renderingReference.RenderingItem.InnerItem.IsOfType(Sitecore.TemplateIDs.Sublayout))
                {
                    var control = renderingReference.GetControl();
                    control.RenderControl(writer); // Throws null reference error in GetCacheKey()
                }
            }
        }
    }

    return sw.ToString();
}

回答1:


In my opinion, the best way to programmatically render a Sublayout is to use a repeater, and put a <sc:Sublayout> tag in the <ItemTemplate>.

From there you only have to do one or both of the following:

  1. Set the DataSource property of the <sc:Sublayout> to be the string representation of the desired item's GUID (i.e. the data source for the sublayout, if any)

  2. Set the Path property of the <sc:Sublayout> to be the path to the Sublayout that you wish to render.

The server/sitecore will handle the rest.



来源:https://stackoverflow.com/questions/15259830/how-to-get-content-of-rendering-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!