Jakub Arnold
Jakub Arnold

Reputation: 87210

How can I output a string in Ember while still having it interpreted by handlebars?

Here's a simple example

MyApp.ApplicationController = Ember.Controller.extend({
  content: "some @user",
  parsedContent: function() {
    return this.get("content").replace("@user", "<a {{action gotoUser 'user'}}>user</a>");
  }.property("content")
});

which will output

some @user
some <a {{action gotoUser 'user'}}>user</a>

instead of interpreting the content as a Handlebars template. I guess I need to compile this manualy, but I'm not sure how to pass the correct context.

Here's a JSFiddle

Upvotes: 1

Views: 538

Answers (1)

Bradley Priest
Bradley Priest

Reputation: 7458

I have a working example here. Basically by making the template of a view a computed property you can modify the template before passing it into the Handlebars parser.

MyApp.LinkedUsersView = Ember.View.extend({
    template: function() {
        template = this.get("content").replace(/@(\w+)/g, '{{view MyApp.UserLinkView username="$1"}}');
        return Ember.Handlebars.compile(template);
    }.property()
});

MyApp.UserLinkView = Ember.View.extend({
    tagName: "span",
    user: function() {
        return MyApp.User.findByUsername(this.get('username'));
    }.property(),
    template: Ember.Handlebars.compile('<a {{action goToUser view.user href=true}}>@{{view.username}}</a>')
}); 

{{view MyApp.LinkedUsersView content="some @user with @another_user"}}

I'm not sure of the performance of compiling the Handlebars template every time though.

Upvotes: 2

Related Questions