kjantzer-backbone-template-data
v0.2.0
Published
Provides alternative to .toJSON() with ability to extend data for templating
Downloads
5
Readme
Backbone.js Template Data
Provides alternative to .toJSON() with ability to extend data for templating
Background
Backbone models have a toJSON
method that prepares the attributes as a JSON object. It is used when sending the model to the server. toTemplate
has been introduced to provide a way of extending the data in toJSON for the purpose of rendering in an HTML template but without modifying what is sent to the server.
Template data takes toJSON
and extends it with the data defined.
Setup
To use, you define a hash of extra data. Hash values can be strings of method names or a function.
let Model = Backbone.Model.extend({
template: {
'full_name': 'fullName',
'extra_data': function(){ return 'Extra data' }
},
fullName(){ return this.get('first')+' '+this.get('last') }
});
Now for using the data
let model = new Model({first: 'John', last: 'Doe'})
console.log(model.toJSON()) // {label: 'My Model'}
console.log(model.toTemplate()) // {first: "John", last: "Doe", full_name: "John Doe", extra_data: "Extra data"}
Applying the data to a template string
let tmpl = '<h1>{{full_name}}</h4>'
// use underscores template engine (or another)
_.template(tmpl, model.toTemplate())
// or you can pass directly to the method (which will use underscores _.template)
model.toTemplate(tmpl) // <h1>John Doe</h4>
Library Support
Child Collections
When using a child model, you can add template: true
to include the data of the child model in your template data.
var Computer = Backbone.Model.extend({
models: {
'employee': {
id: 'employee_id',
coll: myCompany.get('employees'),
template: true
}
}
});
Attribute types
Any specified attribute types will be observed
Changelog
v0.2.0 - 9/14/18
.toTemplate(templateStr)
now accepts an optional template string that will automatically merge the template data into your template
License
MIT © Kevin Jantzer - Blackstone Publishing