EmberJS模板连接

时间:2014-10-06 14:27:36

标签: templates ember.js handlebars.js

如何在EmberJs上的模板上连接字符串(或如何添加类)?

离。

<script type="text/x-handlebars">
// This div I want to add a class go, Is this the right way to do it?
<div class="fly {{isGo}}">Fly now</div>

// Or it's something like this?
<div class="fly "{{isGo}} >Fly now</div>
</script>

2 个答案:

答案 0 :(得分:1)

在Ember指南中对此进行了全面讨论:http://emberjs.com/guides/templates/binding-element-class-names/

但你这样做是这样的:

<div {{bind-attr class="isGo"}}>Fly now</div>

在你的控制器中:

App.MyController = Ember.ObjectController.extend({
    flightIsAGo: true,
    isGo: function() {
        return "fly"+this.get('flightIsAGo') ? ' isGo' : '';
    }.property('flightIsAGo')
}

答案 1 :(得分:0)

bind-attr曾经是解决Ember渲染限制的好方法。现在使用HTMLbars,Ember建议我们离开bind-attr,因为我们有更强大的方法。

  

Ember 1.13弃用了bind-attr以支持新语法。   http://emberjs.com/deprecations/v1.x/#toc_bind-attr

这两个提出的方法的工作示例可以在ember twiddle中看到,这里: https://ember-twiddle.com/38f69f01d2fd994af3b0965f10882005?openFiles=templates.application.hbs%2C

方法1

如果您想在手柄模板中进行组合,可以执行以下操作:

<div class={{concat "fly " isGo}}>Fly now</div>

方法2

否则使用计算属性,如:

  flyingClass: Ember.computed('isGo', function() {
    // return a string with 'fly' and the value of
    // isGo. Will be updated if isGo changes.
    // Array values are created with space delimited by
    // ['className', 'anotherClassName', 'lastClastName'].join(' ');
    // => "className anotherClassName lastClassName"
    let going = this.get('isGo') ? 'going' : ''
    return ['fly', going].join(' ');
  })

然后在你的把手模板中:

<div class={{flyingClass}}>Fly now</div>

这两种方法之间的主要区别取决于您希望如何分离关注点。现在,方法1可能更容易,但随着条件越来越复杂,您可以隐藏计算属性中的更多工作。

相关问题