2012-12-24 76 views
1

這裏有一個簡單的例子如何在Ember中輸出字符串,同時仍然通過車把解釋?

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

將輸出

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

,而不是解釋的內容作爲把手模板。我想我需要編譯這個手冊,但我不知道如何傳遞正確的上下文。

Here's a JSFiddle

回答

2

我有一個工作示例here。 基本上通過使視圖的模板成爲計算屬性,您可以在將模板傳遞到Handlebars解析器之前修改該模板。

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"}} 

我不確定每次編譯Handlebars模板的性能如何。

+0

雖然它似乎工作,它不會數據綁定。嘗試在JSFiddle中執行'MyApp.get(「router.applicationController」).set(「content」,「whatever」)',它不會重新呈現模板。 –

+0

再一次,一個表現的事情,快速解決方法是將把手改爲「{{#with content}} {{view MyApp.LinkedUsersView contentBinding =」this「}} {{with}}' –

+0

或者你也可以創建一個觀察者,當內容改變時重新渲染視圖。 http://jsfiddle.net/bradleypriest/6p6XJ/253/ –

相關問題