template
:_
<div id="page-directory"></div>
<script type="text/template" id="template-site">
<% if(featured) { %>
<span class="featured"></span>
<% } %>
<a href="http://google.com"><img class="screenshot" src="content/screenshot.png" /></a>
<div>
<h2><a href="<%- url %>"><%- title %></a></h2>
<p><span>Tags:</span><%- tags %></p>
<p class="colors"><span>Colors:</span><%- colors %></p>
</div>
</script>
model
和view
:_
// Define a Site Model.
var Site = Backbone.Model.extend({
defaults: {
url: '',
title: '',
featured: false,
tags: '',
colors: ''
}
});
// Define a Site View.
var SiteView = Backbone.View.extend({
tagName: "article",
template: _.template($("#template-site").html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
collection
和collection view
:_
// Define a Sites Collection.
var Sites = Backbone.Collection.extend({
url: 'sites.php',
model: Site
});
// Define a Sites View.
var SitesView = Backbone.View.extend({
el: $('#page-directory'),
initialize: function() {
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
addOne: function(site) {
var siteView = new SiteView({model: site});
this.$el.append(siteView.render().el);
},
addAll: function() {
this.collection.forEach(this.addOne, this);
},
render: function() {
this.addAll();
}
});
并sites.php
返回:
<?php
$sites = array(
array(
'title' => 'CGART',
'url' => 'http://google.com',
'featured' => true,
'tags' => '<a href="http://google.com">Tag 1</a>' .
'<a href="http://google.com">Tag 1</a>' .
'<a href="http://google.com">Tag 1</a>',
'colors' => '<a href="http://google.com" style="background-color: #000000;"></a>' .
'<a href="http://google.com" style="background-color: #ffffff;"></a>',
),
array(
'title' => 'CGART',
'url' => 'http://google.com',
'featured' => true,
'tags' => '<a href="http://google.com">Tag 1</a>' .
'<a href="http://google.com">Tag 1</a>' .
'<a href="http://google.com">Tag 1</a>',
'colors' => '<a href="http://google.com" style="background-color: #000000;"></a>' .
'<a href="http://google.com" style="background-color: #ffffff;"></a>',
),
);
print json_encode($sites);
在这种情况下tags
,colors
是 HTML,我的代码将它们输出如下:
我的模板有什么问题?