简体   繁体   English

Javascript模板库,用于推断使用过的变量和依赖项

[英]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? 是否有一个Javascript模板库可以自动推断模板中使用的变量以及它们之间可能存在的依赖关系? If I for example have a template that looks like this ( Handlebars syntax): 例如,如果我有一个看起来像这样的模板( Handlebars语法):

<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 . 此代码段(在http://jsfiddle.net/CfaAW/2/上编辑)使用正则表达式来查找简单的{{var}}语法,并且还会查找. to handle Handlebars Paths. 处理Handlebars路径。

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: 在您的模板上, JSON.stringify(extractObjectFromTemplate(source))为您提供:

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

and with Handlebars Paths in your template 以及模板中的Handlebars Paths

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

you will get the nested properties 您将获得嵌套属性

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM