【问题标题】:How to apply jquery mustache to external file/template如何将 jquery mustache 应用于外部文件/模板
【发布时间】:2011-10-15 21:47:22
【问题描述】:

目前我正在使用它来“获取”我的外部 html 文件,然后使用 mustache 附加到该模板的 ID:

 $.get('block.html', function(data) {
        $('#mydiv').append(data);

            var list = {
                       name : 'whatever'  
            };

            $('#Block').mustache(list).appendTo('#mydiv');
    });

文件 block.html 看起来像:

<script id="Block" type="x-tmpl-mustache">
My name is {{name}}
</script>

现在,有没有更好的方法来做到这一点,因为目前我要追加两次?

【问题讨论】:

    标签: jquery ajax templates external mustache


    【解决方案1】:

    嗯,当模板位于当前文档中时,jquery mustache 插件非常适合。

    但是在这里你有一个不同的用例,mustache 本身提供的助手足以完成这项工作。所以,只是:

    $.get('block.html', function(template) {
        var view = {name:'whatever'};
        var html = Mustache.to_html(template, view);
        // and now append the html anywhere you like
    });
    

    在这种情况下,你的 block.html 可以变成:

    My name is {{name}}
    

    【讨论】:

      【解决方案2】:

      您可以使用我编写的库 Chevron 从文件中加载外部模板,如下所示:

      在 HTML 中添加指向模板文件的链接:

      <link href="path/to/template.mustache" rel="template" id="templateName"/>
      

      然后,在你的 JS 中你可以像这样渲染你的模板:

      $("#templateName").Chevron("render", {name: "Slim Shady"}, function(result){
          // do something with 'result'
          // 'result' will contain the result of rendering the template
          // (in this case 'result' will contain: My name is Slim Shady)
      });
      

      Chevron 的文档将提供更多示例

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-31
        • 1970-01-01
        • 2011-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-06
        相关资源
        最近更新 更多