【问题标题】:Handlebars helpers as tags车把助手作为标签
【发布时间】:2014-04-12 01:03:27
【问题描述】:

使用正则表达式,我将字符串中的**text in bold** 替换为<strong>text in bold</strong>,然后在我的EmberJS 模板上使用{{{message}}} 显示message。问题是我还想用{{#link-to "hashtag" "anyhashtag"}} 替换#anyhashtag,它只适用于{{message}}

所以我的想法是创建一个{{strong}}text in bold{{/strong}} 助手,它也会更安全,但显然助手只能像{{strong "text in bold"}} 那样工作,如果我有粗体或更复杂字符串的链接,它将无法工作。

我可以做一个符合我想法的助手吗?

谢谢!

【问题讨论】:

  • 这里发生了很多事情。不确定我是否看到您真正要问的事情。您能否提炼出您的用例、问题所在以及您尝试解决的问题?
  • @ahaurw01 很抱歉造成混乱。

标签: javascript regex ember.js handlebars.js


【解决方案1】:

这是一个有点令人困惑的问题,但我认为这就是您所要求的:

Ember.Handlebars.registerHelper("strong", function (options) {
  options.hash.layout = Ember.Handlebars.compile("<strong>{{yield}}</strong>");
  return Ember.Handlebars.helpers.view.call(this, Ember.View, options);
});

工作demo


实际上,更好的变体是这样的:

Ember.Handlebars.registerHelper("strong", function (options) {
  options.hash.tagName = "strong";
  return Ember.Handlebars.helpers.view.call(this, Ember.View, options);
});

这避免了将&lt;strong&gt; 包装成&lt;div&gt;。如果您需要更复杂的包装器,第一个版本会很有用。更新demo


您似乎正在尝试从用户提供的内容创建动态模板。您不能通过将模板字符串插入{{{}}} 构造来做到这一点。 'Triple-mustache' 用于原始 html 输出,它没有处理其中的额外模板代码的能力。

很遗憾,你也不能直接通过属性编译它。 Handlebars 编译器实际上是在生成一个函数,然后需要使用一堆与 Ember 相关的上下文来调用它才能生成 html。

解决所有这些问题的最佳方法(据我所知)再次是通过视图。像这样:

App.ApplicationController = Ember.Controller.extend({
  text: "text in bold",

  html: function() {
    return Ember.Handlebars.compile("{{#strong}}" + this.get('text') + "{{/strong}}");
  }.property("text")
});
<script type="text/x-handlebars">
  <div>Working: {{#strong}}text in bold{{/strong}}</div>
  <div>Working: {{view Ember.View template=html tagName="span"}}</div>
</script>

这将显示正确的值,但如果您更改它就不会更新。要获取实时更新,请执行以下操作:

App.UpdatableView = Ember.View.extend({
  templateChanged: function () {
    this.rerender();
  }.observes("template")
});
<script type="text/x-handlebars">
  <div>Working: {{#strong}}text in bold{{/strong}}</div>
  <div>Working: {{view App.UpdatableView templateBinding=html tagName="span"}}</div>

  <!-- Type here to see changes -->
  {{input type="text" value=text}}
</script>

更新了现场演示here

更新:当然,既然我明白了你想要做什么,我意识到你并不真正需要答案的第一部分,{{strong}} helper。

【讨论】:

  • 伙计,你真是个天才。但我还有一个小问题,请参阅:emberjs.jsbin.com/jerogiku/4/edit
  • 更新了答案,包含更多信息和新的 jsbin 链接。
  • 效果很好!不过我确实有一个警告:“警告:您正在尝试通过将 templateBinding=html 传递给视图助手来呈现视图,但这种语法不明确。您应该将 html 括在引号中或从 templateBinding 中删除 Binding。”
  • 是的。两者都行。 xxxBinding="something"xxx=something 并希望 Ember 能够接您想要创建绑定。我更喜欢第一个。
  • 嘿@panta82,我发现它实际上在生产中不起作用,因为 Ember.Handlebars.compile 未定义。我该如何解决?
猜你喜欢
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 2013-02-05
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
相关资源
最近更新 更多