简体   繁体   中英

JS templating system with Backbone.js

I am looking at some good templating systems to be used alongwith an MVC framework like Backbone.js

I am aware of one such system (jQuery Templating). However, the same has been discontinued for some reasons and hence I am looking at some other good options.

Please suggest something which is flexible enough from a view perspective. (eg a dynamic view with enabled/disabled button based on some logic, tabular data with different styles based on some logic, etc)

I really like Handlebars.js...

Here's some JavaScript...

var HandlebarsView = Backbone.View.extend({
    el: '#result'
    initialize: function(){
        this.template = Handlebars.compile($('#template').html());
    },
    render: function(){
        var html = this.template(this.model.toJSON());
        this.$el.html(html);
    }
});

var HandlebarsModel = Backbone.Model.extend({});

var model = new HandlebarsModel({
   name: 'Joe Schmo',
   birthday: '1-1-1970',
   favoriteColor: 'blue'
});

var view = new HandlebarsView({
    model: model
});
view.render();

Then the html...

 <div id="result">
 </div>
 <script id="template" type="text/html">
    <div>Name:{{name}} Birthday: {{birthday}} Favorite Color: {{favoriteColor}} </div>
 </script>

Give that a shot!

You have out of the box Underscore's template system .

With example:

# code simplified and not tested
var myView = Backbone.View.extend({
  template: _.template( "<h1><%= title %></h1>" ),

  render: function(){
    this.$el.html( this.template({ title : "The Title" }) );
    return this;
  }
});

All the template systems you can find have an integration similar to this.

Of course this is a simplified example, normally the template is fed with the this.model.toJSON() , also you can find tricks to declare the template body into an <script> tag , and you can use Mustache syntax instead of ERB .

I'm using haml-coffee together with rails asset pipeline.
Quite exotic choice, but works great so far.

Inside view it's simple as that:

var MyView = Backbone.View.extend({
  template: JST['path/to/mytemplate']

  render: function(){
    var html = this.template(this.model.toJSON());
    this.$el.html(html);
  }
})

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM