How to use {{action}} in dynamically loaded element in Handlebars.js?


How to use {{action}} if handlebar template is loaded dynamically?


I think what you want to do here is defining the template of a given view at runtime. We did this as we wanted to have hyperlinks between routes that are being parsed from standard hrefs.

I’ll better just show you the code:

var ArticleContentView = Ember.View.extend({
  template: function() {
    var content = this.get('content');
    // replace anchor links to articles with action helpers (goToArticle)
    // but only the ones like `href="WS012345"`
    content = content.replace(/href="#(WS[0-9]+)"/, 'href="#" {{action goToArticle "$1"}}');
    // compile template
    return Ember.Handlebars.compile(content);
  }.property('content') // observe content for changing the template

Note that there may be some problems with this approach: You should probably escape the string you make a template to defend against XSS attacks or better use this method only on secured inputs.

Also, you need the full Handlebars Library and not only the runtime environment. This will add quiet some additional payload to your site and also template compilation takes its time, so you better not use it too often I’d say.

I hope this is the right way to do it for your problem, Best, Stefan