27

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

这是我的 index.html :

<!DOCTYPE html>
<html lang="fr">
    <head><meta charset="utf-8"></head>
    <body>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
        <script src="../js/jquery.mustache.js"></script>
        <script src="../js/app.js"></script>
        <div id="content"></div>
    </body>
</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($) {

// <snip> 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
  • 重构直到你放弃
$(文档).ready(函数() {
  var template = " ... {{title}} ... ";
  var json = {标题:“标题文章”}
  var article = $.mustache(template, json);
  $("#content").append(article);
});

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

$(文档).ready(函数() {
  var template = " ... {{title}} ... ";
  $.getJSON('../js/article.json', function(view) {
    var article = $.mustache(模板,视图);
    $("#content").append(article);
  });
});

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

$(文档).ready(函数() {
  $.getJSON('../js/article.json', function(view) {
    $.get("../templates/article.mustache", function(template) {
      var article = $.mustache(模板,视图);
      $("#content").append(article);
    });
  });
});

工作示例(没有加载顺序问题):

$(文档).ready(函数() {
  $.getJSON('../js/article.json', function(model) { return onJSON(model); });
});

函数 onJSON(模型){
  $.get("../templates/article.mustache", function(view) {
    var article = $.mustache(view, model);
    $("#content").append(article);
  });
}
4

2 回答 2

11

代替Mustache.to_html,试试$.mustache。在我看来,Mustache变量是在函数中定义的,因此在函数之外无法直接访问。

于 2011-06-22T17:31:26.393 回答
8

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

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

于 2011-10-30T21:24:27.403 回答