Search code examples
javascripttemplatesdependency-managementtemplatingtemplating-engine

Javascript templating library that infers used variables and dependencies


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.


Solution

  • 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.

    function extractObjectFromTemplate(source) {
        var handlebarsRegex = /\{\{([\s\S]+?)\}\}/g;
        var varObject = {};
        var varArray, ns, o, i, len;
        while ((varArray = handlebarsRegex.exec(source)) !== null) {
            ns = varArray[1].split('.');
            o = varObject;
            for (i = 0, len = ns.length; i < len; i++) {
                o = o[ns[i]] = o[ns[i]] || (i == len - 1 ? "" : {});
            }
        }
    
        return varObject;
    }
    

    On your template, a JSON.stringify(extractObjectFromTemplate(source)) gives you this:

    {"title":"","body":""}
    

    and with Handlebars Paths in your template

    <h1>{{title.h1}}</h1>
    <h2>{{title.h2}}</h2>
    <div class="body">
      {{body}}
    </div>
    

    you will get the nested properties

    {"title":{"h1":"","h2":""},"body":""}