Usually I have a dataset with many records like:
data = [
{ name1: value, name2: value },
{ name1: value, name2: value }
];
Want to use one template when there are more than 0 records in my array but want to apply a different template when data is empty like:
data = [];
The {{if}} conditionals work fine when one of the named elements are empty but how do I check if the root array is empty and select a different template based on that?
You can do that various ways, but here is one approach.
Pass your data array to the JsRender template, with the boolean noIteration
flag set to true (see example):
html = myTmpl.render(data, true);
so that the template renders just once, for the array.
Then use a template similar to the following, with a {{for}}
tag to iterate and an {{else}}
for the case where the array is empty...
<script id="myTmpl" type="text/x-jsrender">
{{for}}
this will render once for each item in the array
{{else}}
this will render if the array is empty
{{/for}}
</script>
(See Using the {{else}} tag with {{for}})
Similarly, you can pass in your array as part of the data:
var viewModel = {myArray: data, ...},
html = myTmpl.render(viewModel);
then write:
<script id="myTmpl" type="text/x-jsrender">
{{for myArray}}
this will render once for each item in the array
{{else}}
this will render if the array is empty
{{/for}}
</script>