Search code examples
javascriptjsrender

How do I test a value on a list of objects using jsRender


I'm new to jsRender. On my Model I have something like:

public List<BasketOptions> Basket {get; set;}

I know in jsRender for example I can do:

{{if Basket.length }}

which will return true or false if I have at Basket.

what I'm trying to do and need some help with is that on my BasketOptions object I have a boolean 'Selected' flag. I need to be able to test for any selected flag being true. can anybody offer or point me to a good example of how to do this. I'm assuming I need to call a Javascript function passing my Basket object and determining the value there, but it's how I call that javascript function and return the value for jsRender to test.

So I have created a javascript function:

<script>
   function GetBasketSelected(options) {
   var optionSelected = options.find(function (option) {
     return option.Selected;
   });
   return optionSelected;
}
</script>

and to call the script I have:

{{ if ~GetBasketSelected(Basket) }}
……
{{/if}}

I set a breakpoint in the javascript function in chrome browser and it never gets hit.

So I have also tried the following without luck:

{{ if :~GetBasketSelected(Basket) }}
    ……
{{/if}}

with

<script>
   $.views.helpers({
       GetBasketSelected: function(options) {
       var optionSelected = options.find(function (option) {
         return option.Selected;
       });
       return optionSelected;
    }
   });
</script>

Solution

  • If Selected is a property of Basket, you can write

    {{if Basket.Selected}}...{{/if}}
    

    or

    {{if Basket.Selected===true}}...{{/if}}
    

    But if Selected is a getter function, you would need

    {{if Basket.Selected()}}...{{/if}}
    

    You can also call helper functions:

    {{if ~testSelected(Basket)}}...{{/if}}