3
votes

I'd like to define a block helper that puts the text in the block into a <a href=""></a> tag. I used an example from http://handlebarsjs.com/block_helpers.html as a start but my code doesn't work. What do I have to change to get <a href="http://www.example.com">test</a> as the output of this block helper?

app.js

App = Ember.Application.create();

Handlebars.registerHelper('link', function(options) {
  var result = '<a href="http://www.example.com">' + options.fn(this) + '</a>';
  return Handlebars.SafeString(result);
});

index.html

  <!DOCTYPE html>
  <html lang="en">
    <head>
      <title>Example</title>
    </head>
    <body>
      <script type="text/x-handlebars">
        <p>
        {{#link}}
        test
        {{/link}}
        </p>
      </script>

    </body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/handlebars.js"></script>
    <script type="text/javascript" src="js/ember.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
  </html>
1
I get test and I'd like to get <a href="http://www.example.com">test</a>wintermeyer

1 Answers

5
votes

Just a couple of details (EDITED):

  • You just need to create a new instance of Handlebars.SafeString before returning it. Please check @muistooshort's jsfiddle here with a working example of what you are trying to achieve.

  • Block helpers are a little bit more complex and used when is needed to invoke a section of a template with a different context. If it is not your case, you could use the syntax for regular Handlebars helpers. (I'll leave the following code here for future reference, although it's not relevant in this case)

Declare helper in app.js:

Ember.Handlebars.registerHelper('link', function(value) {
  var result = '<a href="http://www.example.com">' + value + '</a>';
  return new Handlebars.SafeString(result);
});

In index.html replace your current template with:

<script type="text/x-handlebars">
  <p>
    {{link test}}
  </p>
</script>

Hope this helps!