如何在 Ember 中创建可以 wrap/manipulate 内容的 Handlebars 块助手?
How do you create a Handlebars block helper in Ember that can wrap/manipulate content?
我想创建一个包装和转义内容的 Handlebars 块助手(用于 Ember 应用程序)。我认为它会相对简单,但我花了几个小时在上面却一无所获。我想要这个:
{{#code}}
<p>Hey!</p>
{{/code}}
变成这样:
<pre>
<code>
<p>Hey!</p>
</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.
我想创建一个包装和转义内容的 Handlebars 块助手(用于 Ember 应用程序)。我认为它会相对简单,但我花了几个小时在上面却一无所获。我想要这个:
{{#code}}
<p>Hey!</p>
{{/code}}
变成这样:
<pre>
<code>
<p>Hey!</p>
</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.