如何在Ember中创建一个Handlebars块帮助器来包装/操作内容

How do you create a Handlebars block helper in Ember that can wrap/manipulate content?

本文关键字:帮助 包装 操作 Handlebars 一个 Ember 创建      更新时间:2023-09-26

我想创建一个Handlebars块帮助器(在Ember应用程序中使用)来包装和转义内容。我以为它会相对简单,但我花了几个小时,却一无所获。我想要这个:

{{#code}}
  <p>Hey!</p>
{{/code}}

变成这个:

<pre>
  <code>
    &lt;p&gt;Hey!&lt;/p&gt;
  </code>
</pre>

我能得到的最接近的是:

Em.Handlebars.registerHelper('code', function(options) {
  options.fn()
})

但这只是直接输出块中的内容。我不能包装或操纵它。我错过了什么明显的东西吗?当然,这并不像看起来那么难。

自定义助手可能不得不依赖私有API,这在Ember中变化非常频繁-特别是现在引入了Glimmer渲染引擎。你可能会更好地使用Ember.Component,使用{{yield}}渲染html到一些隐藏的容器,然后使用didInsertElement钩子手动操作DOM使用jQuery,例如

x-code.hbt

<div class="to-escape" style="display: none">{{yield}}</div>
<pre>
  <code>        
  </code>
</pre>

x-code.js

App.XCodeComponent = Ember.Component.extend({
  didInsertElement: function() {
    var value = this.$('.to-escape').html();
    this.$('code').text(value);
  }
});

作为

{{#x-code}}
  <p>Hey!</p>
{{/x-code}}

JsBin例子。