Reputation: 591
I want to create a Handlebars block helper (to use in an Ember app) that wraps and escapes content. I thought it would be relatively simple, but I've spent hours on it and gotten nowhere. I want this:
{{#code}}
<p>Hey!</p>
{{/code}}
To become this:
<pre>
<code>
<p>Hey!</p>
</code>
</pre>
The closest I've been able to get is this:
Em.Handlebars.registerHelper('code', function(options) {
options.fn()
})
But that just outputs the content in the block straight away. I can't wrap it or manipulate it. Am I missing something obvious? Surely this can't be as difficult as it seems.
Upvotes: 1
Views: 214
Reputation: 1293
Custom helper would probably have to rely on private API which changes quite frequently in Ember - specially now as Glimmer rendering engine is being introduced. You will be probably better off with just using Ember.Component
, using {{yield}}
to render html into some hidden container, and then using didInsertElement
hook to manipulate DOM manually using jQuery, e.g.
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);
}
});
and use it as
{{#x-code}}
<p>Hey!</p>
{{/x-code}}
Example JsBin.
Upvotes: 1