我想用用jQuery mustache.js在我的HTML5应用程序,但我不能让所有的组件协同工作。每个文件都找到了,这里没有问题(模板加载了roght,我可以在Firebug调试器中看到它的值)。Mustache.js + jQuery:最简单的工作示例是什么?
这里是我的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
函数代替(在案githu B)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); }); }); });
工作示例(无l oading顺序问题):
$(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); }); }
我会把所有的JavaScript **放在**内容后面。 [LINK](http://developer.yahoo.com/blogs/ydn/posts/2007/07/high_performanc_5/) – Sparky
感谢您的提示。我现在不在寻找优化,我蚂蚁让我的代码工作 –
我发布它作为评论,而不是答案。当然,您在其中加载脚本的**命令**也包括_also_,以使代码正常工作。如果你是JavaScript的初学者,这个信息是一个关键的'必读'。所有初学者都知道他们需要加载jQuery _before_他们加载jQueryUI或任何其他jQuery插件? – Sparky