2011-10-15 39 views
2

目前我使用这“获得”我的外部HTML文件,然后用胡子来追加到模板的ID:如何将jQuery小胡子应用到外部文件/模板

$.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> 

现在,有没有更好的方式做到这一点,因为此刻我追加两次?

回答

7

那么,当模板在你当前的文档中时,jquery胡子插件非常适合。

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

$.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}} 
+0

的伟大工程。谢谢 – odle

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) 
}); 

雪佛龙的文档会举些例子