So, i'm simply trying to convert an int to a bool inside of an "if" statement. I'm unsure on how to achieve this. My code that I was playing with is below.
The HTML:
<div id="main-div"></div>
<script id="testTmpl" type="text/x-jsrender">
<input data-link="{:test:}" />
<div data-link="{intToBool:test:}"></div>
// testing different methods, none seem to work
{^{if intToBool:test }}
Woot! 1
{{/if}}
{^{if intToBool(test) }}
Woot! 2
{{/if}}
{^{if ~root.intToBool(test) }}
Woot! 3
{{/if}}
</script>
The JavaScript:
$.views.converters({
intToBool: function(val) {
if (val === 0 || val === false || val === '0' || val === 'false') {
return false;
} else {
return true;
}
}
});
function App(data) {
self = this;
self.test = 0;
};
var app = new App();
var testTmpl = $.templates("#testTmpl");
testTmpl.link("#main-div", app);
Registering converters is only for use with the {{: ...}}
tag (http://www.jsviews.com/#assigntag) in it's various forms {{cvt:expression}}
{^{cvt:expression}}
<div data-link="{cvt:expression}">
or <input data-link="{cvt:expression:cvtBack}" />
. See http://www.jsviews.com/#converters.
For other scenarios you need to use either a method {^{if someMethodOnMyModel(test)}}
or a helper (http://www.jsviews.com/#helpers): {^{if ~someHelper(test)}}
.
See also http://www.jsviews.com/#samples/jsr/paths for examples of helper paths - ~some.expression...
- to either helper function or helper objects. Note that ~root
is a built-in helper path to the top-level data object that you passed in to render()
or link()
.
Edit: In fact there is a little-known feature in JsRender and JsViews which does let you associate registered converters with other tags. You can write
{^{if test convert="intToBool" }}
Woot!
{{/if}}
But generally it may be simpler/better to use ~intToBool(test)
- which is more familiar, and perhaps easier to understand when reading the template.
Also BTW {{if test}}
tests on 'truthy' so test
does not need to be of type boolean. OTOH if you want to make "false", or "0" be falsey, then you will indeed need a helper/converter.