For my next blog post I needed to investigate how to use a custom Group Display Template for the Search Results WebPart. Unfortunately you can only set the Control Display Template and the Item Display Template in the Search Results WebPart properties.
If you want to specify the group display template, you have two options:
- Creating your own Search Results WebPart by extending the default one
In this post I’m only going to explain the second option because I wanted to define it in my custom display templates. It’s also easier to have only one Search Results WebPart, so that you do not have to worry when to use which web part.
- Make the Search Results WebPart think that it’s an Content Search WebPart
- Overriding the default grouping template reference
- Using the set_groupTemplateId function
I found the first method when I compared the properties of the context from Search Results WebPart and the Content Search WebPart.
Search Results WebPart
Content Search WebPart
The Content Search WebPart has a Group template property which isn’t set on the Search Results WebPart. This property can be accessed via ctx[‘ClientControl’].$j_4
To set the $j_4 property, you can use this piece of code:
_Note: when I did some tests on Office 365, I found out that it’s using a different property: ctx[‘ClientControl’].$e_4. _
When the property isn’t set in the previous method, it retrieves the reference from the RenderTemplateId property.
You can set the RenderTemplateId property like this:
I found out that there is a better method when I was checking the Search.ClientControls.debug.js file. It turn out that you have a function called: set_groupTemplateId(value).
The last thing that needs to be done is to include the custom Group Display Template script in the custom (or default) Control Display Template from the Search Results WebPart.
Added the third method.