I am trying to upgrade from the old jQuery tmpl to this awesome new jsRender.
My code is already working.
I am building a FORM with templates based on a JSON returned by the backend.
The object is:
var form = {
name: "addNew",
fields: [{type: "text", name: "Age"}, {type: "hidden", name: "Id"}]
};
In the old jQuery plugin I did like this
'{{tmpl(this.data) selectInputTemplate( this.data )}}'
Where the function selectInputTemplate() will return the template name based on the field type.
How would this work in the new jsRender ?
EDIT:
How can I access the entire object ? In old jQuery Template was with this.data.
I created a helper function to return me the template, but I need to know how to access the entire object to send it to helper.
EDIT 2:
This is ugly but it is working:
var form_field_wrap =
"{{if type === 1 tmpl='form_field_input_text' /}}" +
"{{if type === 2 tmpl='form_field_input_select' /}}" +
"{{if type === 3 tmpl='form_field_input_checkbox' /}}" +
"{{if type === 4 tmpl='form_field_input_radios' /}}" +
"";
In the template you can access the entire contextual data object, using #data
.
(See Paths and expressions)
In a helper function, the this
object is generally the current view
object, so you can get the data object as this.data
.
Here is an example that shows both the above methods:
<script id="myTmpl" type="text/x-jsrender">
{{include tmpl=~getTmpl(#data)/}}
</script>
<div id="page"></div>
<script>
var myTmpl = $.templates("#myTmpl"),
data = { name: "Jo" },
helpers = {
getTmpl: function(data) {
return $.templates("{{: 123}}" + data.name + this.data.name);
}
},
html = myTmpl.render(data, helpers);
$("#page").html(html);
</script>
Incidentally, you can write your example with {{if}}
tags like this
"{{if type === 1 tmpl='form_field_input_text'}}" +
"{{else type === 2 tmpl='form_field_input_select'}}" +
"{{else type === 3 tmpl='form_field_input_checkbox'}}" +
"{{else type === 4 tmpl='form_field_input_radios'}}" +
"{{/if}}"