【问题标题】:Compile template client side in ember using HTMLbars使用 HTMLbars 在 ember 中编译模板客户端
【发布时间】:2015-07-30 18:15:03
【问题描述】:

我创建了一个 CMS,可以在其中使用 HTMLbars 创建模板。模板应该在客户端编译,并且有应该显示模板的组件。我正在将组件的模板属性设置为使用 HTMLBars 返回已编译模板的函数。

import Ember from 'ember';

export default Ember.Component.extend({
  content: null,
  template: function () {
    return Ember.HTMLBars.compile(this.get('content.template'));
  }
}

我已经在我的 Brocfile 中包含了 ember-template-compiler。

app.import('bower_components/ember/ember-template-compiler.js');

也测试过

app.import('bower_components/ember-template-compiler/index.js');

但是模板永远不会被渲染。

【问题讨论】:

    标签: ember.js htmlbars


    【解决方案1】:

    它应该是一个属性,在组件上应该是layout,但它只会被评估一次,所以更新内容不会重建模板。

    http://emberjs.jsbin.com/vayereqapo/1/edit?html,js,output

    Ember.Component.extend({
      content: {template: 'Hello'},
      layout: function () {
        return Ember.HTMLBars.compile(this.get('content.template'));
      }.property()
    });
    

    模板内容改变时重新渲染:

    App.FooBarComponent = Ember.Component.extend({
      content: {template: 'Hello'},
      foo: function(){
        var self = this;
        Em.run.later(function(){
          self.set('content.template', 'Bye');
          self.rerender();
        }, 3000);
      }.on('init'),
      layout: function () {
        return Ember.HTMLBars.compile(this.get('content.template'));
      }.property('content.template')
    });
    

    http://emberjs.jsbin.com/qebuxuxasu/1/edit

    【讨论】:

    • 感谢您的回答。重新渲染会触发布局重新编译吗?
    • 显然会的,每天都学点新东西 :) emberjs.jsbin.com/qebuxuxasu/1/edit
    • 我对其进行了测试,并且该属性已经存在,但在我的示例中只是缺少它。但是我有一个旧模板 hbs 文件连接到具有优先权的组件。删除文件后,它也可以与模板一起正常工作。
    • 有没有办法验证编译好的模板?现在,每当模板出现故障时,它就会中断。我想在将其插入 dom 之前对其进行验证。
    • ember-template-compiler.js 在 JSBin 中,但值得指出的是,除了 Ember 本身之外,您还必须加载它。
    猜你喜欢
    • 2016-09-17
    • 2014-04-09
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    相关资源
    最近更新 更多