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

Jea*_*ana 25 javascript jquery html5 mustache

我想在我的HTML5应用程序中使用带有jQuery的mustache.js,但我不能让所有组件一起工作.找到每个文件,这里没有问题(模板加载roght,我可以在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>
Run Code Online (Sandbox Code Playgroud)

这是我的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);
    });
});
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

显示注释.萤火虫告诉我

小胡子没有定义

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

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

谢谢.


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

  • 在脚本中写入模板,不要从文件中加载它
  • 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);
  $("#content").append(article);
});

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

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

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

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

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

$(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);
    $("#content").append(article);
  });
}

Eli*_*ria 11

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


Xou*_*boy 6

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

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