Dynamic JSRender Condition from JSON
-
Is it possible to include a jsrender condition in the JSON object which will then be evaluated at render time?
e.g. if I have this JSON object, with a dynamic condition, I want it to be evaluated in the "if" below to show or hide html depending on if it evaluates to true or false.
{
"age": 13,
"condition": "age > 18"
}
<div>
{{if condition}}
This text shows if age > 18
{{/if}}
</div>
In the above, this would obviously always evaluate as "truthy" because it is not evaluating the condition itself. Is it possible to interpret this as an expression to be evaluated by jsrender?
-
You can just implement your own
if
helper and dynamically evaluate condition based on your needs.
https://playground.jsreport.net/w/anon/gzpL4h0dfunction myIf(condition) { console.log(this.tagCtx.view.data) const r = evalInScope(condition, this.tagCtx.view.data) if (r === true) { return this.tagCtx.render(this.tagCtx.view.data) } return 'nothing to show' } function evalInScope(js, contextAsScope) { //# Return the results of the in-line anonymous function we .call with the passed context return function() { with(this) { return eval(js); }; }.call(contextAsScope); }
Note I would encourage you to use handlebars instead as its more widely adopted in jsreport. All the new office recipes implementation supports just the handlebars and this trend will likely continue.
-
Thank you!
We'd like to use handlebars instead, but is it possible to do the same thing with handlebars?
-
Yes of course.
https://jsreport.net/learn/handlebars
https://handlebarsjs.com/
-
Here is the same in handlebars
https://playground.jsreport.net/w/anon/kVF0KiLj
-
You're amazing thank you!