简体   繁体   English

带有Backbone.js的JS模板系统

[英]JS templating system with Backbone.js

I am looking at some good templating systems to be used alongwith an MVC framework like Backbone.js 我正在寻找一些好的模板系统,以及像Backbone.js这样的MVC框架

I am aware of one such system (jQuery Templating). 我知道一个这样的系统(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... 我真的很喜欢Handlebars.js ......

Here's some JavaScript... 这是一些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... 然后是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 . 你有开箱即用的Underscore模板系统

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 . 当然这是一个简化的例子,通常模板是用this.model.toJSON() ,你也可以找到将模板体声明<script>标签的技巧,你可以使用Mustache语法而不是ERB

I'm using haml-coffee together with rails asset pipeline. 我正在使用haml-coffee和rails资产管道。
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);
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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