如何将jquery胡子应用于外部文件/模板

时间:2011-10-15 21:47:23

标签: jquery ajax templates external mustache

目前我使用它来“获取”我的外部html文件,然后使用小胡子附加到该模板的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>

现在,是否有更好的方法可以做到这一点,因为目前我正在追加两次?

2 个答案:

答案 0 :(得分:7)

好吧,当模板在当前文档中时,jquery 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}}

答案 1 :(得分: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)
});

雪佛龙的文档将提供更多示例