2013-08-29 44 views
5

我已經實現了頁面標題,並且所有頁面都整齊地顯示標題。 現在我也想顯示網站名稱。 我可以像如何在Yii中設置Sitename頁面標題

<title><?php echo Yii::app()->name . $this->pageTitle ?></title> 

但對於其標題沒有設置(即他們是默認設置由CController)網站名稱將得到重複的網頁代碼時。

我想簡單地覆蓋控制器的setPageTitle方法來預先安裝sitename。如何做?

+0

這就是所謂的編程正常。如果你想重寫,看看你想重寫的現有代碼來獲得一些指針。你到目前爲止看到了什麼,以及你在哪裏碰到路障? (嘗試解決覆蓋在你的問題中缺失) – hakre

回答

3

這是我解決了嘗試覆蓋CController的setPageTitle方法的問題

class MyController extends Controller 
{ 
    public function setPageTitle($value){ 
    $this->pageTitle = Yii::app()->name ." >> ". $value ; 
    } 
} 

現在的這個值將在佈局不應用程序名稱即

<title><?php echo CHtml::encode($this->pageTitle); ?></title> 

設置,並在視圖中刪除的應用程序名稱。

$this->pageTitle = Yii::app()->name . ' >> Custom Title' ;//remove this to show instead 
$this->pageTitle = 'Custom Title' ;//Plain title 

現在輸出將是

我的應用程序名稱>>自定義標題

如果一些頁面已經爲那些你需要重寫控制器視圖連接在一起的應用程序名稱只有那些控制器中的setPageTitle。但更好的方法是始終遵循一個常見的事情,因此覆蓋基本控制器中的setPageTitle。

0

在每個控制器,添加該屬性變量:

class MyController extends Controller { 

    public $pageTitle = 'My Custom Title'; 

同樣,您可以覆蓋每個控制器的佈局:

class MyController extends Controller { 

    public $layout = '//layouts/myCustomLayout'; 
+0

你爲什麼不把它放在AppController中?少寫多少。 – Fortuna

+0

op需要爲每個控制器使用不同的默認部分標題。 –

4

您不必添加$pageTitle控制器它已經是Controller類中的一個變量,所以只要你的控制器extend Controller你應該沒問題。然後,您可以在任何需要的位置設置頁面標題。您可以更改整個控制器,或個別操作甚至視圖。

class MyController extends Controller { 
    public function actionAdmin() { 
     $this->pageTitle = 'I got set by action'; //only for this action 
    } 
} 

或者在一個視圖

<?php 
$this->pageTitle = 'I got set by the view'; //anytime this view gets called 
?> 
<h1>View File</h1> 

如果在標題的最後希望網站名稱總是簡單地修改您的主要佈局:

<title><?php echo CHtml::encode($this->pageTitle); ?> <?php echo Yii::app()->name; ?></title> 
1

如果你想要更多的東西 '自動',例如:

  • 始終在PAGETITLE 「動作+控制器」。示例:查看用戶,刪除用戶...

您可以製作一個這樣的過濾器:(也適用於多國語言!!!)

由1-保護/組件創建一個文件PageTitleFilter.php/

class PageTitleFilter extends CFilter { 

    public $controller; 

    protected function preFilter($filterChain) { 
     // logic being applied before the action is executed 
     $this->controller->pageTitle = Yii::t('app', Yii::app()->controller->action->id) . ' ' . Yii::t('app', Yii::app()->controller->id); 
     return true; // false if the action should not be executed 
    } 

    protected function postFilter($filterChain) { 
     // logic being applied after the action is executed 
    } 

} 

2。在你的控制器:

class MyController extends Controller { 

    public function filters() { 
     return array(
      'accessControl', // perform access control for CRUD operations 
      array(
       'PageTitleFilter + view, create, update, delete, admin', 
       'controller' => $this 
      ), 
     ); 
    } 
} 

然後你把保護的文件/郵件/ ES /每個動作的翻譯app.php,如:

return array(
    'view'=>'ver', 
    'delete'='eliminar' 
); 

鏈接:http://www.yiiframework.com/doc/guide/1.1/es/topics.i18n#locale-and-language

如果要更改默認PAGETITLE,你可以在任何動作做:

$this->pageTitle= 'My page title'; 

如果你不想多語言,取出的Yii :: T(「應用」)的功能!

相關問題