This post was something that has been on my to-do list for quite some time, and was also requested by a couple of people. So finally I found the time to work this out.
Back in SharePoint 2010 and 2007 we could easily group the results in the Content Query Web Part, but this functionality isn’t included in the Content Search Web Part. In this post I’ll how I achieved grouping of the search results with display templates.
How I did it
You have a couple approaches to achieve this. My approach is to create a new current context ctx variable, and add an grouping object to it. In this grouping object I’ll store the HTML content for its corresponding group. For this approach a control and item display template needs to be created. In the control template the object is created, and will be filled up from data coming from the item template. In the control template a post render event is required to visualize the array values.
This is the code which is in the DIV container of the control template:
The currentCtx.Grouping object will be filled with data from the item template with the HTML code of the result and the corresponding group value. In the estruyf.Grouping.init method, you find the AddPostRenderCallback method which will call the estruyf.Grouping.show method to visualize the HTML content.
First of all for the item template I configured the following ManagedPropertyMapping:
The Grouping property is the most important one, this is be used for configuring on which field the grouping needs to be set. The reason I went for this approach is that you can easily configure the field to set up the grouping on (in the next section how to use it, I’ll describe how to use the templates, and how to set up another field to group on).
The next step is the code:
How to use it
When you place the control and item display templates in the master page gallery of your site (the link to the files is at the bottom of the page), the following two templates become available in your Content Search Web Part:
By default, it will sort everything on the Site Title managed property. This looks like this:
You could also change the grouping property if you want. This can be done by overwriting the property mappings in the web part properties:
The result will look a bit different now:
How to change the HTML output
If you want to change the HTML output, you will need to do two things:
- In the item template you need to change the HTML which is stored in the content variable;
- In the control template you need to update the HTML code which is written in the estruyf.Grouping.show method.
My display templates can be downloaded from the SPCSR GitHub project: Result Grouping Templates (CSWP)
The code for this solution has been updated. Now the grouping object is not added on the ctx object, but it is added on our own currentCtx object.