Search code examples
javascriptsharepointdisplay-templates

Sharepoint Display Templates How to use Group Display Template


the code in the control display template uses _#= ctx.RenderGroups(ctx) =#_ and there is another JS file named group_content.js that is being called, how do i split my data into groups in order to render some HTML per group?


Solution

  • After intensive research, you need to do some manually to use it.

    1. Create Group Display Template file, just take the default "group_xxx.html" from the "Search" or "Content Search" Folders, whatever you are using.

    2. MUST download a copy or you Search WebPart (export) and change the value in "GroupTemplateId" to your group JS file.

    3. CODING objects to mimic ResultTables object

    final code

    ctx.ClientControl.set_groupTemplateId('~sitecollection/_catalogs/masterpage/display templates/content web parts/Group_Content_QA.js');
    ctx.ListDataJSONGroupsKey = "ResultGrouped"
    ctx.ListData.ResultGrouped = [];
    
    //function to create the ResultTables fake array
    function createResultGroup(items){
     return {
      ResultRows: items, 
      RowCount: items.length,
      TableType: "RelevantResults",
     }
    };
    
    //just a ref
    var _items = ctx.ListData.ResultTables[0].ResultRows;
    
    //categories dictionary
    var _groupDictionary = {};
    
    //populating dictionary categories
    _items.forEach(function(e) {
        if ( !_groupDictionary[e.QACategoryOWSCHCS] ){
       _groupDictionary[e.QACategoryOWSCHCS] = [];
        }
    });
    
    //populating dictionary categories with items
    _items.forEach(function(e) {
     _groupDictionary[e.QACategoryOWSCHCS].push(e);
    });
    
    //adding to ctx categories as a named array
    ctx.groupsNames = Object.keys(_groupDictionary);
    
    //populating fake ResultTables array (ResultGrouped)
    ctx.groupsNames.forEach(function(g) {
     ctx.ListData.ResultGrouped.push(
      createResultGroup(_groupDictionary[g])
     );
    });
    

    read more here