Skip to content

Instantly share code, notes, and snippets.

@parrya
Created October 22, 2021 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parrya/20bf1f20ccafa6336dc6c668db4e5ff5 to your computer and use it in GitHub Desktop.
Save parrya/20bf1f20ccafa6336dc6c668db4e5ff5 to your computer and use it in GitHub Desktop.
Override Initialize method of RenderJsonRendering
using System.Collections.Generic;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.LayoutService.Configuration;
using Sitecore.LayoutService.ItemRendering;
using Sitecore.LayoutService.Presentation.Pipelines.RenderJsonRendering;
using Sitecore.LayoutService.Serialization;
using Sitecore.Mvc.Presentation;
using System.Linq;
namespace JSSDemo.Foundation.LayoutService.PipelineProcessors
{
public class CustomInitialize : Initialize
{
IRenderingConfiguration _renderingConfiguration;
public CustomInitialize(IConfiguration configuration) : base(configuration) { }
protected override RenderedJsonRendering CreateResultInstance(RenderJsonRenderingArgs args)
{
_renderingConfiguration = args.RenderingConfiguration;
//Note: the constructor below is different for Sitecore 9.x and 10. The below will only work in Headless Services for Sitecore 10.
return new RenderedJsonRendering()
{
Name = args.Rendering.RenderingItem.Name,
DataSource = args.Rendering.DataSource,
RenderingParams = SerializeRenderingParams(args.Rendering),
Uid = args.Rendering.UniqueId
};
}
protected virtual IDictionary<string, string> SerializeRenderingParams(Rendering rendering)
{
IDictionary<string, string> paramDictionary = rendering.Parameters.ToDictionary(pair => pair.Key, pair => pair.Value);
foreach (string key in paramDictionary.Keys.ToList())
{
if (ID.TryParse(paramDictionary[key], out var itemId))
{
Item item = rendering.RenderingItem.Database.GetItem(itemId);
paramDictionary[key] = _renderingConfiguration.ItemSerializer.Serialize(item, new SerializationOptions() { DisableEditing = true });
}
}
return paramDictionary;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment