Saturday 17 November 2018

Renderings static binding

Last time I had to prepare a component which behaves like a carousel of specific type of renderings. Instead of copy-pasting the Razor markup or using basic Razor partials I decided to use static binding of renderings - method I've never used before. It appeared to be extremely handy.

Basically you can specify a rendering like this:

@Html.Sitecore().Rendering("{ rendering ID }", new { Cacheable = true, Cache_VaryByData = true, DataSource = "{ DataSource ID}" })

First parameter is rendering ID, second is anonymous object where we can specify additional properties, like caching or even datasource that will be used there.

You can even add your custom properties and read them inside rendering, just like this:

@Html.Sitecore().Rendering(
    Constants.MyRendering.RenderingId.ToString("B"),
    new
    {
        Cacheable = true,
        Cache_VaryByData = true,
        DataSource = myDatasource.Id.ToString("B"),
        MyProperty = "My custom value"
 })

To be more familiar with possible properties of that anonymous object I have decompiled GetRendering method from SitecoreHelper class:


I have created and extension method to easily retrieve rendering properties:

And you can use it in view like this:

var property = Html.Sitecore().GetRenderingProperty("MyProperty");