An idea where I’m currently working on involves sorting of the search results in display templates. So I thought it would be interesting to share this information already. You will see that enabling sorting, won’t involve a lot of code. You just need to know what you need to do, before you can start sorting the results.
How to implement it
I created a copy of the Control_ListWithPaging.html control template. I chosen this template, because if you are going to sort a set of search results, this will be on the whole set, not only the ones that are displayed. So by using the paging control template, you can step through the pages to see the other results in a sorted order.
Important: sorting could only work if the managed property is sortable. You could check this in your search schema.
First of all, what you need to do if you want to add sorting to your display template, is to register the sorting properties on the data provider which your display template will be using.
For this post I’ll use the creation date, which is linked to the Created managed property.
In the code above I added two sorting options, ascending sorting and descending sorting for the creation date. As you can see in the push method is a JSON string value which contains two attributes:
- Sorts: here you define the sorting: p = managed property name, d = direction - 0 = ascending / 1 = descending.
Once you add these sorting options to the array, they need to be registered in the DataProvider with the set_availableSorts method.
Now that the sorting options are set to the data provider object, it is time to visualize these sorting options. The visualization can be done with the following piece of HTML code:
Important: sorting could only work if you set the query builder to build the query in advanced mode. Once in advanced mode, the sorting tab becomes available. If you’ll use the predefined queries, the sorting won’t do anything to the set of results.
This is the result if you added this to your control template:
Results in ascending order
Results in descending order
My display templates can be downloaded from the SPCSR GitHub project: Result Sorting Template (CSWP).