Я хотел бы использовать mustache.js с jQuery в своем приложении HTML5, но я не могу заставить весь компонент работать вместе. Каждый файл найден, здесь нет проблем (шаблон загружен roght, я могу видеть его значение в debugguer 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);
Отмечается. Firebug сообщает мне
Усы не определены
Смотрите захват:
Я знаю, что чего-то не хватает, но я не могу сказать, что.
Спасибо.
ИЗМЕНИТЬ: Правильный и полный ответ на минимальный пример:
- напишите шаблон в script, не загружайте его из файла
- idem для данных json
- прочитайте, как генерируется jQuery, и используйте функцию
$.mustache.to_html
вместо (документально подтвержденной на github)Mustache.to_html
(благодаря @mikez302) - refactor ', пока вы не упадете
$(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); }); }