我想在我的 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); }); }