我喜欢 Node.js 中 Jade 模板引擎的类似 HAML 的语法,我喜欢在 Backbone.js 中的客户端使用它。
我见过 Backbone 通常使用以下样式的 Underscore.js 模板。
/* Tunes.js */
window.AlbumView = Backbone.View.extend({
initialize: function() {
this.template = _.template($('#album-template').html());
},
// ...
});
/* Index.html */
<script type="text/template" id="album-template">
<span class="album-title"><%= title %></span>
<span class="artist-name"><%= artist %></span>
<ol class="tracks">
<% _.each(tracks, function(track) { %>
<li><%= track.title %></li>
<% }); %>
</ol>
</script>
我希望看到一种使用 AJAX(或其他方法)获取 Jade 模板并在当前 HTML 中呈现它们的方法。
最佳答案
我能够使用 jade-browser 运行 Jade 客户端项目。
与 Backbone 的集成非常简单:我使用 jade.compile()
而不是 _template()
。
HTML(脚本和模板):
<script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://raw.github.com/weepy/jade-browser/master/jade.js"></script>
<script src="https://raw.github.com/weepy/jade-browser/master/jade-shim.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script type="template" id="test">
div.class1
div#id
| inner
div#nav
ul(style='color:red')
li #{item}
li #{item}
li #{item}
li #{item}
script
$('body').append('i am from script in jade')
</script>
JavaScript(与 Backbone.View 集成):
var jade = require("jade");
var TestView = Backbone.View.extend({
initialize: function() {
this.template = jade.compile($("#test").text());
},
render: function() {
var html = this.template({ item: 'hello, world'});
$('body').append(html);
}
});
var test = new TestView();
test.render();
HERE 是代码。
关于javascript - 在 Backbone.js 中使用 Jade 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8528885/