Search code examples
javascriptember.jshandlebars.jsember-cli

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


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>
    &lt;p&gt;Hey!&lt;/p&gt;
  </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.


Solution

  • 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.