【问题标题】:Modify John Resig's microtemplating engine to replace "new Fun" or "eval"修改 John Resig 的微模板引擎以替换“new Fun”或“eval”
【发布时间】:2012-08-12 14:42:18
【问题描述】:

如何修改John Resig's microtemplating 引擎使其不使用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;
    };
})();

【问题讨论】:

标签: javascript jquery templates jquery-templates


【解决方案1】:

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

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

【讨论】:

  • 不。它将输出作为“
  • 又看了一些,我没有看到一个简单的解决方案。您确实需要评估从“str ...”中出来的字符串才能使其正常工作。所以是的,它变成了 eval 或 Function 或任何类似的东西。编辑了我的答案;)
【解决方案2】:

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

但是,由于您需要它使其在 Chrome 中运行,您可以转换自己的代码以使用 lower privileged sandbox, designed specially to run code with eval and like

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2011-11-08
    • 2011-09-19
    相关资源
    最近更新 更多