Is there a Javascript templating library that automatically infers the variables used in the template and the possible dependencies among them? If I for example have a template that looks like this (Handlebars syntax):
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
I would like to be able to do something like this:
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
template.vars() => {title: "", body: ""}
The reason I would like this functionality is that I would like to be able to generate a form with fields reflecting the variables needed to complete the template.
This snippet (edit at http://jsfiddle.net/CfaAW/2/) uses a Regex to find the simple
{{var}}
syntax, and will also look for.
to handle Handlebars Paths.On your template, a
JSON.stringify(extractObjectFromTemplate(source))
gives you this:and with Handlebars Paths in your template
you will get the nested properties