【问题标题】:template inside html mustache jshtml mustache js中的模板
【发布时间】:2013-03-17 16:45:33
【问题描述】:

我正在使用 mustache 来呈现 html 的一部分。为此,我正在使用这个 javascript:

   var template = $("#div_name").html();
   ..
   ..
   $("#container").append(Mustace.render(template,some_object));

由于<div id="div_name"></div> 仍然保留在 html 中,我只使用它来获取我想知道的模板:将模板化的div html 保留在 html 中是否方便,或者更好的是 load 它例如部分通过ajax ? 提前致谢。

【问题讨论】:

    标签: javascript jquery templates mustache


    【解决方案1】:

    您还可以将模板保留在脚本元素中,如下所示:

       <script type="application/mustache" id="div_name">
           //Mustache template code here
       </script>
    

    然后使用$("#div_name").html() 从那里获取模板代码。由于type无效,不会显示在页面上,并且脚本标签没有被执行。

    【讨论】:

    • 首先,谢谢。我从未见过这种解决方案,但通常我会避免在 javascript 中使用 HTML,因为它经常抛出由空格引起的错误。我做错了吗?
    • @steo 是的,就像我解释的那样,您应该像我一样指定type。如果您指定application/mustache 之类的类型,浏览器将不会将其作为javascript 执行。看这里,没有错误:jsfiddle.net/nZQ32
    • 如果我有多个模板怎么办?我必须为每个脚本创建一个脚本?
    • @steo 是的,任何解决方案都必须这样做。
    猜你喜欢
    • 2011-11-10
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    相关资源
    最近更新 更多