【问题标题】:Precompile mustache templates or load externally?预编译 mustache 模板或从外部加载?
【发布时间】:2013-10-29 22:26:56
【问题描述】:

有一个 Coffeescript 包含函数会很有用,这样它可以在用 javascript 编译时加载外部 mustache 模板,而不会弄乱咖啡文件。

实际上您可以在运行时加载 .mustache 文件,但您需要使用 ajax 请求调用它们,这会涉及一些性能损失。

我想预编译一些静态 mustache 模板并将它们包含在生成的 JavaScript 函数中,该函数可以是 Stitched 并压缩在单个文件中。

有相应的项目或脚本吗?

【问题讨论】:

    标签: javascript coffeescript mustache


    【解决方案1】:

    我认为这个解决方案适合你,用于 mustache 和其他模板引擎的 javascript 模板预编译器 https://github.com/kupriyanenko/jsttojs

    例如,与命令行一起使用

    jsttojs templates compiled/templates/index.js --ext mustache --watch
    

    或使用 grunt 解决方案,grunt-jsttojs

    【讨论】:

    • Stack Overflow 不欢迎仅链接的答案。请在此处添加信息。
    • 当然欢迎。但是很高兴将答案带给您,并在 SO 上存档,以防链接到的解决方案发生更改/404 或其他任何可能使仅链接无用的情况。
    【解决方案2】:

    首先你可以使用这样的东西:

    <script type="text/x-mustache" id="tid...">
      ... mustache template ...
    </script>
    

    将您的模板包含在专用脚本块中,而不是作为代码中的字符串。 getElementByID() + innerHtml() 将为您提供可以使用的源代码。

    关于一般的 Mustache - 你不能严格地编译它。每次您“实例化”模板时都会解释模板。

    如果您确实需要编译它们,请考虑使用我的 Kite 引擎: http://code.google.com/p/kite/ 或任何其他可编译模板: http://jsperf.com/dom-vs-innerhtml-based-templating/99

    【讨论】:

      【解决方案3】:

      当然,这是我们在我工作的地方所做的事情。所有模板都放在一个 html 文件中,并在构建时插入到 dom 中。每个模板都存储在未知类型的脚本标签中,因此浏览器会忽略它。然后你可以使用选择器来引用它们。

      <script type="unknown" id="id_of_template">
        <ul>
        {{#words}}
          <li>{{.}}</li>
        {{/words}}
        </ul>
      </script>
      
      render = (template) ->
        view =
          words: [ 'hello', 'there' ]
        template = $('#' + template).html()
        html = Mustache.to_html template, view
      

      John Resig 有一篇关于该技术的好文章 http://ejohn.org/blog/javascript-micro-templating/

      【讨论】:

      • 另一个答案谈到使用“text/x-mustache”作为脚本类型。为什么不这样做呢?
      • 没有理由做或不做。该类型仍然无法被识别,但如果它更清楚地表明它是一个 Mustache 模板,那么它可以工作。
      • 我是这么认为的.. 几乎在那个时候只是一个文档问题
      【解决方案4】:

      我正在考虑做类似的事情。我还没有尝试过,但您似乎可以使用 Node.js 和 Mu(Node.js 的 Mustache 构建)来执行此操作。伪JS代码...

      var compiledTemplate = Mu.compile("myTemplateFile.html")
      fs.writeFile("myCompiledTemplate.js", compiledTemplate.toString());
      

      【讨论】:

      【解决方案5】:

      Twitter 的库 Hogan.js 可以完成这项工作。

      【讨论】:

        【解决方案6】:
        猜你喜欢
        • 1970-01-01
        • 2012-03-14
        • 1970-01-01
        • 2017-12-06
        • 1970-01-01
        • 1970-01-01
        • 2015-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多