7
votes

I have an Ember template that is rendering text with a Handlebar expression, i.e. {{caption}}. The text being rendered has hashtags in it, each of which I need to make clickable, and going to a specific route in the Ember app.

I created a helper to parse the text and replace each hashtag with a link to the necessary route combined with the hashtag, so now the Handlebar expression looks like: {{clickable-hashtags caption}}. However, the helper creates the links using regular HTML <a href> tags, and this is returned using Ember.Handlebars.SafeString.

I would like to use Ember's {{#link-to}} helper method for each hashtag instead, but can't seem to figure out how to do that. Is it possible for Handlebars to parse out the link-to tags within the template's {{caption}} expression?

3

3 Answers

5
votes

Well, you could do it with an computed property

The caption:

This is my #hashtag caption

In controller:

   computedCaption: function () {
     var words = caption.split(" ");
     return words.map(function (e) {
        var isHashtag = e.charAt(0) === "#";
       return {isHashtag: isHashtag, text: e};
     });
   }.property("computedCaption")

Template:

{{#each computedCaption as |cap|}}
   {{#if cap.isHashtag}}
      {{#link-to 'tags' cap.text}}{{cap.text}}{{/link-to}}
   {{else}}
   {{cap.text}}
   {{/if}}
{{/each}}

Result

This is my #hashtag caption

JS Bin: http://emberjs.jsbin.com/kohubu/1/

Computed properties @ Emberjs

0
votes

The problem I see with doing it that way is not being able to bind variables (and helper results) to the link-to helper. The work around I would use would be to use actions and to move your helper logic into the controller.

Define the transitionTo action in the application route:

App.ApplicationRoute = Ember.Route.extend({
    events: {
        transitionTo: function (route) {
            this.transitionTo(route);
        }
    }
});

Template:

{{#each item in controller.captions}} <!-- or instead use model-->
    <li>
        <a {{action 'transitionTo' item.route}}> <!-- without hashtags -->
            {{item.label}} <!-- with hashtags -->
        </a>
    </li>
{{/each}}
0
votes

Have you considered doing client-side HTML compilation?

I'm thinking you'll need to install the necessary helpers (i.e. link-to) and pass in variable values. This test may be of some help getting there.