Mustache.js + jQuery:什么是最小的工作示例?

我想在我的HTML5应用程序中使用带有jQuery的mustache.js,但我不能让所有组件一起工作。 找到每个文件,这里没有问题(模板加载roght,我可以在Firebug调试器中看到它的值)。

这是我的index.html:

       

这是我的app.js文件:

 $(document).ready(function() { var template = $.get('../templates/article.mustache'); $.getJSON('../js/article.json', function(view) { var html = Mustache.to_html(template, view); $("#content").append(html); }); }); 

jquery.mustache.js文件是从https://github.com/janl/mustache.js生成的文件:

 /* Shameless port of a shameless port @defunkt => @janl => @aq See http://github.com/defunkt/mustache for more info. */ ;(function($) { //  mustache.js code $.mustache = function(template, view, partials) { return Mustache.to_html(template, view, partials); }; })(jQuery); 

显示注意。 萤火虫告诉我

小胡子没有定义

看到捕获: 在此处输入图像描述

我知道缺少一些东西,但我不知道是什么。

谢谢。


编辑最小例子的正确和完整答案如下:

  • 在脚本中写入模板,不要从文件中加载它
  • json数据的同义词
  • 阅读如何生成jQuery并使用$.mustache.to_html函数而不是(记录在github上) Mustache.to_html (感谢@ mikez302 )
  • 重构’直到你掉下来
 $(document).ready(function(){
   var template =“... {{title}} ...”;
   var json = {title:“titre article”}
   var article = $ .mustache(template,json);
   $( “#内容”)追加(条);
 });

但是,从另一个文件中读取json很容易:

 $(document).ready(function(){
   var template =“... {{title}} ...”;
   $ .getJSON('../ js / article.json',function(view){
     var article = $ .mustache(template,view);
     $( “#内容”)追加(条);
   });
 });

您最后还可以从文件中读取模板:

 $(document).ready(function(){
   $ .getJSON('../ js / article.json',function(view){
     $ .get(“../ templates / article.mustache”,function(template){
       var article = $ .mustache(template,view);
       $( “#内容”)追加(条);
     });
   });
 });

工作示例(没有加载订单问题):

 $(document).ready(function(){
   $ .getJSON('../ js / article.json',function(model){return onJSON(model);});
 });

 function onJSON(model){
   $ .get(“../ templates / article.mustache”,function(view){
     var article = $ .mustache(view,model);
     $( “#内容”)追加(条);
   });
 }

代替Mustache.to_html ,尝试$.mustache 。 在我看来, Mustache变量是在函数中定义的,所以它不能直接在它之外访问。

我知道这个问题已经得到了解答,但是我写了一篇关于这个主题的博客文章,并且认为我会在这里分享它,所以任何寻找如何使用jQuery的Mustache的例子的人都可以看到它。

http://blog.xoundboy.com/?p=535