public
Last active

view helpers for underscore

  • Download Gist
1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var data = {
type: "something",
name: "whatever",
addresses: [
{
type: "read_address",
address: "1/2/3",
value: "10"
},
{
type: "write_address",
address: "1/2/4"
}
]
}
2.html
HTML
1 2 3 4 5 6 7
<script id="my-template" type="text/template">
<p>type: <%= type %></p>
<p>name: <%= name %></p>
<p>read address: <%= _.find(this.addresses, function(addr){ return addr.type == "read_address" }).address %> </p>
<p>read address value: <%= _.find(this.addresses, function(addr){ return addr.type == "read_address" }).value %> </p>
<p>write address: <%= _.find(this.addresses, function(addr){ return addr.type == "write_address" }).address %> </p>
</script>
3.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13
var viewHelpers = {
getAddress: function(type){
var address = _.find(this.addresses, function(addr) {
return addr.type == type
});
return address;
}
}
 
 
_.extend(data, viewHelpers);
 
_.template(myTemplate, data);
4.html
HTML
1 2 3 4 5 6 7
<script id="my-template" type="text/template">
<p>type: <%= type %></p>
<p>name: <%= name %></p>
<p>read address: <%= getAddress("read_address").address %> </p>
<p>read address value: <%= getAddress("read_address").value %> </p>
<p>write address: <%= getAddress("write_address").address %> </p>
</script>
5.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13
Backbone.View.extend({
template: "#my-template",
 
render: function(){
 
var data = this.model.toJSON();
_.extend(data, viewHelpers);
 
var html = _.template($(this.template), data);
this.$el.html(html);
 
}
});
6.js
JavaScript
1 2 3 4 5 6
Backbone.Marionette.ItemView.extend({
 
template: "#my-template",
templateHelpers: viewHelpers
 
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.