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

问题描述 投票:0回答:3

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

<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}}"
,字面意思,以及模态标题。

而且......不,现在我不考虑将“标题”作为新参数传递并在模式中使用它。另一个模板中的模态标题可能不是“New {{title}}”,而是“你确定吗?”或“有关

{{title}}
的详细信息”。

ember.js handlebars.js custom-component
3个回答
62
投票

您正在寻找的是concat助手。使用它,你的第二个例子将变成:

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

3
投票

我来这里寻找handlebars.js 中的

concat
助手。如果有人登陆这里寻找相同的东西有用,handlebars-helpers 有一个内置的
append
帮助器。

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

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


0
投票

是的,传递标题就是我的做法。如果您需要向标题添加的内容不仅仅是

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?

© www.soinside.com 2019 - 2024. All rights reserved.