Data source and children content resolver

If you worked on a Sitecore JSS implementation you must be familiar with the Rendering Content Resolvers used by the Layout Service to serialize the contents of a rendering data source into JSON. Out of the box, Sitecore comes with the following Rendering Content Resolvers


  • Datasource Resolver 
    •  The default resolver which serializes the data source item
  • Datasource Item Children Resolver 
    • Serializes the datasource item's children
  • Context Item Resolver
    • Serializes the context item instead of the data source item
  • Context Item Children Resolver
    •  Similar to Datasource Item Children Resolver but serializes the children of the context item
  • Folder Filter Resolver
    • Serializes not just direct children but also the descendants of the data source item, excluding folders

As you can see, there is no out of the box contents resolver that can serialize both the data source item and its children. This will be handy when you have a module that contains a parent data source item and children items created directly underneath, for e.g. Content cards module like below


Without a data source and children content resolver, you need to write a GraphQL query to resolve both parent and child items in one go. 

Creating a custom DatasourceItemAndChildrenContentsResolver is simple and straight forward. We need to create a new class that inherits from Sitecore.LayoutService.ItemRendering.ContentsResolvers.RenderingContentsResolver and override the ResolveContents method.

From the code above, you can see we are not only resolving the contents of the data source item (in line 21) but also resolving the contents of children (in line 28) and adding them to a new children property of the JSON object.

Once you have your custom Rendering Contents Resolver ready, you need to deploy the code to your Sitecore instance and define a new Rendering Contents Resolver under /sitecore/system/Modules/Layout Service/Rendering Contents Resolvers/ node of the content tree.


Once the new custom Rendering Contents Resolver is defined, you need to update you rendering definition's Rendering Contents Resolver field with the DatasourceItemAndChildrenContentsResolver you just created.


With the DatasourceItemAndChildrenContentsResolver the layout service JSON output for the data source item includes the children as shown below


Hope this helps you with similar requirement that you may have or with writing your own custom Rendering Content Resolver for your specific requirements. 

Comments

Popular posts from this blog

How to ace your Sitecore .Net Developer 10 Certification Exam

Running SQL Queries On Sitecore Databases Using Sitecore PowerShell Extensions

SXA Scriban extension to get link field target URL