WIP: jsrender recursive template
HTML
<ul id="results"></ul>
<script id="reflectTemplate" type="text/x-jquery-tmpl">
<li>
{{#if $ctx.isArray($data)}}
[
<ul>
{{each $data tmpl="#reflectTemplate"}}
</ul>
]{{#if $ctx.notLast($view)}},{{/if}}
{{else $ctx.isObject($data)}}
[OBJECT not dissected]
{{else}}
{{=$ctx.formatDisplay($data)}}
{{/if}}
</li>
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/BorisMoore/jsrender/master/jsrender.js"></script>
JavaScript
/*global $ */
$(function () {
"use strict";
$.views.registerHelpers({
isObject: function (item) {
return null !== item && "object" === typeof (item);
},
isArray: function (item) {
return null !== item && "object" === typeof (item) && item instanceof Array;
},
notLast: function (view) {
return view.itemNumber !== view.parent.data.length;
},
formatDisplay: function(propertyValue) {
var toSmallDateString = function(value) {
var padTwo = function(num) {
return (num < 10) ? "0" + num : String("") + num;
};
return padTwo(value.getFullYear()) + "-" + padTwo(1 + value.getMonth()) + "-" + padTwo(value.getDate()) + "," + padTwo(value.getHours()) + ":" + padTwo(value.getMinutes()) + ":" + padTwo(value.getSeconds());
},
propertyType = String(typeof(propertyValue)),
result = propertyValue;
if (null === result) {
result = "null";
}
else if ("string" === propertyType) {
if (propertyValue.indexOf("/Date(") === 0) {
result = toSmallDateString(new Date(parseInt(propertyValue.substr(6), 10)));
}
else {
result = "\"" + result + "\"";
}
}
return result;
}
});
// NOTE: Array elements === 0 are not rendered, hence [1, 2, 3] (https://github.com/BorisMoore/jsrender/issues/31).
$("#results").html($("#reflectTemplate").render([[1, 2, 3], ["ab", "bc", "cd"]]));
});