2013-10-30 55 views
2

我正在構建我的第一個Ember應用程序,但不知何故我無法使其正常工作。將網站標題傳遞給應用程序模板

在我的網站模板呈現在應用程序模板的出口。然後有一些路由到不同的網站。每個網站都有不同的標題。應用程序模板具有該標題的佔位符。

但是,如何顯示與底層站點控制器有關的特定標題(index,about,...)?

我在這裏找到這裏:Setting page title with ember.js但它不適合我。有沒有適當的方法來做到這一點?或者我真的必須給我的h1標籤一個id並將其設置爲jQuery?

Jsbin:http://jsbin.com/ucanam/1912/edit

+0

這應該讓事情變得簡單,但林不知道這是否可用。 https://github.com/emberjs/ember.js/pull/2757 – blessenm

回答

2

你需要設置你的模板的上下文的title屬性。 對於應用程序模板,這是App.ApplicationController

App.IndexRoute = Ember.Route.extend({ 
    activate: function() { 
    this.controllerFor('application').set('title', "Home"); 
    } 
}); 

要設置文檔標題,只要標題改變就可以添加觀察者。

App.ApplicationController = Ember.Controller.extend({ 
    titleDidChange: Ember.observer(function(){ 
    document.title = this.get('title'); 
    }, 'title') 
}); 

http://jsbin.com/ucanam/1921/edit

2

如果要更改標題中的所有路線,你可以重新打開Ember.Route類:

Ember.Route.reopen({ 
    activate: function() { 
    this._super.apply(this, arguments); 
    var title = this.get('title') || ''; 
    document.title = title; 
    } 
}); 

所以在您的路線定義title屬性,將使document.title轉換到該路線時更改。

例如:

App.IndexRoute = Ember.Route.extend({ 
    title: 'index' // changes the title to index 
}); 

App.FooRoute = Ember.Route.extend({ 
    title: 'foo' // changes the title to foo 
}); 

App.BarRoute = Ember.Route.extend({ 
    title: 'bar' // changes the title to bar 
}); 

App.NotitleRoute = Ember.Route.extend({}); // don't change the title 

觀察:這implemantation不具有約束力知道

請給看看。源代碼http://jsbin.com/ucanam/1918/edit。嵌入式演示http://jsbin.com/ucanam/1918