Search code examples
javascriptjsrenderjsviews

JsViews / JsRender table rendering with GroupBy an attribute/property


I am using JsViews to design a template. However I wonder if we can groupBy an attribute based on its string value?

JSON sample:

"ItemDetails": [
    {
        "Amount": 2000,
        "Name": "Horror Book",
    },
    {
        "Amount": 3500,
        "Name": "Horror Book",
    },
    {
        "Amount": 1000,
        "Name": "Children Book",
    },
],

Current code is outlining each item even if it has the same name.

{{for ItemDetails}}
{{if Amount}}
            <row>
                <col>{{>Name}}</col>
                <col>{{>Amount}}</col>
            </row>
{{/if}}
{{/for}}

I want it to have result like this:

Horror Book 5500

Children Book 1000


Solution

  • JsRender/JsViews {{for}} and {{props}} tags have built-in support for sorting, filtering etc, but don't have a built-in groupBy feature. But you can fairly easily create one, following similar techniques to the grid with ~total() sample.

    Here is an approach using helper functions:

    <table><tbody>
      {{for ItemDetails sort="Name"}}
        {{if ~groupBy("Name", "Amount")}}
          <tr>
            <td>{{>Name}}</td>
            <td>{{>~total()}}</td>
          </tr>
        {{/if}}
      {{/for}}
    </tbody></table>
    

    https://jsfiddle.net/BorisMoore/nx3atd1q/

    And here is an alternative version using the filter feature on {{for}}:

    <table><tbody>
      {{for ItemDetails sort="Name" filter=~groupBy groupTotal="Amount"}}
        <tr>
          <td>{{>Name}}</td>
          <td>{{:~total()}}</td>
        </tr>
      {{/for}}
    </tbody></table>
    

    https://jsfiddle.net/BorisMoore/o4pt3brq/