将字符串模板转换为可用的ember模板

时间:2015-10-19 20:00:30

标签: ember.js

我的api为我提供了'[[user]] commented on 6 images'等模板字符串,然后是{user: {val: 'Daniel', id: '...'}}等数据对象。

我正在试图找出如何帮助将其转换为可用的HTMLBars模板,为用户添加链接到组件并输出它。所以基本上让助手返回类似

的东西
'{{link-to user.val 'user' user.id}} commented on 6 images'

实际上可以在模板中使用。

我尝试了Ember.HTMLBars.template('{{link-to ...}} commented...')的某些内容,但不确定如何从那里开始。我是否需要包含ember-template-compiler?我想尽量避免它,因为它为vendor.js增加了几百kbs。如果改变了什么,我也会使用ember-cli。

2 个答案:

答案 0 :(得分:0)

您通常不希望直接创建HTMLBars模板。尝试重构代码,以便使用组件或路径模板。

答案 1 :(得分:0)

您可以制作自定义助手:

// app/helpers/custom-template.js
import Ember from 'ember';

export function customTemplate([ template, data ]) {
  return template.replace(/\[\[(.*?)\]\]/, (_, id) => data[id].val);
}

export default Ember.Helper.helper(customTemplate);

您可以自己实施逻辑(就像我一样)或使用Handlebars。

用法:

{{custom-template commentTemplate commentData}}

export default Ember.Controller.extend({
  commentTemplate: '[[user]] commented on 6 images',
  commentData: {
    user: {val: 'Daniel', id: '...'}
  }
});

更新

您可以将模板分解为一系列链接和非链接,然后按顺序呈现它们

// app/components/custom-template.js
import Ember from 'ember';

export default Ember.Component.extend({
  parts: function() {
    return this.get('templateString').split(/(\[\[.*?\]\])/).map(token => {
      let match = token.match(/\[\[(.*?)\]\]/);
      if (match) {
        let type = match[1];
        let { val, id } = this.get('data')[type] || {};
        return {
          isLink: true,
          type, // 'user'
          val, // 'Daniel'
          id // '123'
        };
      }
      return token;
    });
  }.property('templateString')
});


// app/templates/components/custom-template.hbs
{{#each parts as |part|}}
  {{#if part.isLink}}
    {{link-to part.val part.type part.id}}
  {{else}}
    {{part}}
  {{/if}}
{{/each}}

用法:

{{custom-template templateString=commentTemplate data=commentData}}

export default Ember.Controller.extend({
  commentTemplate: '[[user]] commented on 6 images',
  commentData: {
    user: {val: 'Daniel', id: '123'}
  }
});

输出:

<div class="ember-view" id="ember389">
    <a class="ember-view ember-transitioning-in" href="/user/123" id="ember397">Daniel</a>
     commented on 6 images
</div>