Filtering and sorting arrays with jsrender does not work



  • I cannot get jsrender to filter or sort an array in a for loop. I made an example in Playground, but unfortunately it disappeared. I can recreate it, but I need to know how to save it first.

    Here is how I tried to filter:

    //JSON data:
    {
      "things": [
        {
           "type": 1,
           "name": "thing of type 1"
        },
        {
           "type": 1,
           "name": "another thing of type 1"
        },
        {
           "type": 2,
           "name": "thing of type 2"
        }
      ]
    }
    
    //jsrender loop
    {{for things filter=~filterFunction}}
    
    {{/for}
    
    //filter function
    function filterFunction(item) {
      console.log('this line never gets called');
      return item.type === 1;
    }
    

    I also tried other array functions which don't need a helper function. But I couldn't get this to work either:

    {{for things sort="type"}}
    
    {{/for}}
    


  • The reason is that the filter function is not yet implemented in the jsrender used in jsreport. We will make sure it is updated in the next version.

    However in the meantime... You can filter or sort the array using your own custom helper function.

    {{for ~f(items)}}
      {{:#data}}
    {{/for}}
    
    // your filtering sorting or whatever you need
    function f (items) {   
        return items.filter(i => i > 3)
    }
    


  • Thanks, that explains it.
    A custom function is my solution for now, but it would be cleaner to have it directly in the loop definition.

    Are there any other areas that are not implemented? It would be nice to know before starting to struggle with the next problem (if one exists).



  • Unfortunately, jsrender doesn't have some good release notes. So it is a bit tricky to find out. However, you can do it this way.
    These links are for currently used jsrender version.

    1. Get the jsreport-jsrender version here
    2. Get jsrender version here
    3. See the docs/demos for particular version here


  • Oh, it's a jsrender version issue. I thought maybe the functionality from jsrender was only partially implemented. This is great news (I think). I hope it's not a big deal for you to upgrade the jsrender version. Templating syntax is hard enough even with documentation that match the implementation.



  • I like jsrender very much, but I have now converted my reports to Handlebars. This makes it much easier when searching for help. Handlebars is much more widely used and all jsreport examples (and most forum q&a) are in Handlebars syntax.


Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.