Your help appreciate to learn the way to do this, Lets say I have a code similar to this one.
Backbone script:
$(function(){
var Band = Backbone.Model.extend();
var BandList = Backbone.Collection.extend({
model: Band,
url: 'feed1.json'
});
var BandsView = Backbone.View.extend({
template: _.template($('#bandlist_template').html()),
render: function(eventName) {
_.each(this.model.models, function(band){
var lTemplate = this.template(band.toJSON());
$(this.el).append(lTemplate);
}, this);
return this;
}
});
var lBands = new BandList;
var AppView = Backbone.View.extend({
el: "body",
render: function(){
var lBandsView = new BandsView({model:lBands});
var lHtml = lBandsView.render().el;
$('#bands').html(lHtml);
},
initialize: function(){
var lOptions = {};
lOptions.success = this.render;
lBands.fetch(lOptions);
}
});
var App = new AppView;
});
Underscore js Template:
<script type="text/template" id="bandlist_template">
<?php echo "hello"; ?><li><%= band_name %> - <%= section %></li>
</script>
HTML:
<ul id="bands">
</ul>
Json:
[
{
"id": "149",
"band_name": "Armthorpe Elmfield",
"section": "Fourth"
},
{
"id": "127",
"band_name": "Barnsley Chronicle",
"section": "Second"
},
{
"id": "155",
"band_name": "Barnsley Metropolitan Band",
"section": "Fourth"
}
]
Ok. Lets say I want to change css
style according to json
section
attribute (just only need to put div and style only json section
attribute is 'Fourth'
). So how to filter that attribute and push it into another backbone js populated div
inside the same ul
.
Just like this one:
<ul id="bands">
</li>Armthorpe Elmfield - <div class="styled">Fourth</div><li>
</li>Barnsley Chronicle - Second<li>
</li>Barnsley Metropolitan Band - <div class="styled">Fourth</div><li>
</ul>
You have everything you need, just use the template:
<script type="text/template" id="bandlist_template">
<?php echo "hello"; ?>
<li><%= band_name %> -
<% if section is 'Fourth': %>
<div class="styled">Fourth</div>
<% else: %>
<%= section %>
<% end %>
</li>
</script>
Of course it could be made better but just to prove the point that if
and other control structure work no problem in your templates. (In the example I am using eco
syntax in the if, just fix it to use normal javascript if you need it).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.