在 Handlebars.js 辅助参数中连接字符串和变量的明智方法?

Sane way to concat string and variable in Handlebars.js helper argument?

我正在尝试在 Ember 中构建一个简单的模态组件,但似乎 Handlebars 的 "logic-less" 对我来说太不合逻辑了。有什么理智的方法可以达到这样的结果吗?

<h2>Nice block about {{title}}</h2>
<a href="#" data-toggle="modal" id="add-item-{{title}}"> {{!this works}}

{{#my-modal modal-id="add-item-{{title}}" header='New {{title}}'}} {{! those don't}}
  <p>My body blabla</p>
{{/my-modal}}

目前,我最终得到的模态 ID 是 "add-item-{{title}}",从字面上看,模态标题也是如此。

并且...不,现在我不考虑将 "title" 作为新参数传递并在模态中使用它。另一个模板中的模态 header 可能不是 "New {{title}}" 而是 "are you sure?" 或 "details about {{title}}".

是的,传递标题就是我的做法。如果你需要在标题中添加一些不仅仅是 model.title 的东西,那么在你的控制器上填充一个计算的 属性(es6 字符串插值语法):

控制器

  modalHeader: function() {
    return `New ${this.get('model.title')}`;
  }.property('model.title')

模板

{{#my-modal header=modalHeader}}
  <p>My body blabla</p>
{{/my-modal}}

至于 id,您可以在组件中做一些有趣的事情来覆盖它,请参阅 this codepen,但我不知道它与 ember 有什么关系。你为什么要为模态设置一个 id?

您要查找的是 concat helper。使用它,您的第二个示例将变为:

{{#my-modal modal-id=(concat 'add-item-' title) header=(concat 'New ' title)}} 
  <p>My body blabla</p>
{{/my-modal}}

我来这里是为了在 handlebars.js 寻找 concat 帮手。如果它对登陆这里寻找相同的人有用,handlebars-helpers 有一个内置的 append 助手。

{{> my-modal modal-id=(append "add-item-" title) header=(append "New " title)}}

https://github.com/helpers/handlebars-helpers