2

如何修改John Resig 的微模板引擎,使其不应该使用new Func or eval. 我想要相同的行为,但没有new Func

/ Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function () {
    var cache = {};

    this.tmpl = function tmpl(str, data) {
        // Figure out if we're getting a template, or if we need to
        // load the template - and be sure to cache the result.
        var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

        // Generate a reusable function that will serve as a template
        // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");

        // Provide some basic currying to the user
        return data ? fn(data) : fn;
    };
})();
4

2 回答 2

0

我没有看到一个简单的解决方案。您确实需要评估从“str ...”中出来的字符串才能使其正常工作。所以是的,它变成了 eval 或 Function 或任何类似的东西。

如果您不想这样做,您需要放弃 John 的想法,即您将模板解析为 JS 字符串,然后对其进行评估...... :)

于 2012-08-16T09:39:27.640 回答
0

出于明显的性能原因,许多模板引擎将模板编译为使用数据作为参数的函数,并使用生成的 JS 代码对其进行处理,而不是在每个输出上运行昂贵的模板解析并实现自己的表达式引擎。通常,摆脱编译的唯一方法是完全重写引擎或使用另一个引擎,所以不,不可能只是“修改”它。

但是,由于您需要它使其在 Chrome 中运行,您可以转换您自己的代码以使用较低权限的沙箱,该沙箱专门设计用于运行eval类似.

于 2012-08-16T13:02:27.260 回答