The approach shown below allows razor views to be statically attached to presentation elements without creating rendering elements.
In the layout.cshtml file layout.cshtml statically bind a razor view that does not have a rendering representation view element in Sitecore, and specify the DataSource element:
@Html.Sitecore().ViewRendering("/views/StandaloneRendering.cshtml", new { DataSource = "/sitecore/content/Home/My Datasource Item" })
The appearance of the StandaloneRendering.cshtml razor is as follows:
@using Sitecore.Mvc.Presentation @model RenderingModel @functions { public Sitecore.Data.Items.Item Item { get { var item = Sitecore.Context.Item; if (!string.IsNullOrEmpty(Model.Rendering.DataSource)) { item = Sitecore.Context.Database.GetItem(Model.Rendering.DataSource); } return item; } } } <p>Item Name: @Model.PageItem.Name</p> <p>Datasource Path: @Model.Rendering.DataSource</p> <p>Datasource Item Name: @Item.Name</p> <p>Datasource Item Path: @Item.Paths.FullPath</p> <p>Datasource Item Template: @Item.TemplateName</p>
The following data is displayed on the page:
Item Name: Home Datasource Path: /sitecore/content/Home/My Datasource Item Datasource Item Name: My Datasource Item Datasource Item Path: /sitecore/content/Home/My Datasource Item Datasource Item Template: Sample Item
A few things to know about:
- Sitecore fields displayed in razor view are not editable in the Page Editor.
- I highly doubt that the output of
StandaloneRendering.cshtml will make it in the HTML sitecore cache. - The
Item property in the @functions block must be moved to some place so that it can be reused for several types of razors. - This is a non-standard approach. This may confuse some people who expect to find a related rendering element in Sitecore.
source share