如何设置控制器操作的页面标题?

bag*_*man 6 php controller yii

我希望每个控制器和动作都有不同的标题(头部).怎么从控制器这样做?

bri*_*iiC 10

你的控制器

    class SiteController {
        public function actionIndex() {
            $this->pageTitle = 'Home page';
            //...
        }

        //..
    } 
Run Code Online (Sandbox Code Playgroud)

布局文件

    <title><?php echo $this->pageTitle; ?></title>
Run Code Online (Sandbox Code Playgroud)

也许你忘了在你的HTML中添加引用?


Jon*_*Jon 8

如果您想在每个操作中使用不同的标题

然后只需设置CController.pageTitle操作内部的值:

class MyController extends CController {
    public function actionIndex() {
        $this->pageTitle = "my title";
        // other code here
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要在多个操作之间共享特定标题

一种方法是简单地遵循上述方法,可能使用类常量作为页面标题:

class MyController extends CController {
    const SHARED_TITLE = "my title";

    public function actionIndex() {
        $this->pageTitle = self::SHARED_TITLE;
        // other code here
    }

    public function actionFoo() {
        $this->pageTitle = self::SHARED_TITLE;
        // other code here
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当您要在"标题共享"方案中包含或排除每个操作时,这需要您单独访问每个操作.没有这个缺点的解决方案是使用过滤器.例如:

class MyController extends CController {
    public function filters() {
        // set the title when running methods index and foo
        return array('setPageTitle + index, foo');

        // alternatively: set the title when running any method except foo
        return array('setPageTitle - foo');
    }

    public function filterSetPageTitle($filterChain) {
        $filterChain->controller->pageTitle = "my title";
        $filterChain->run();
    }

    public function actionIndex() {
        // $this->pageTitle is now set automatically!
    }

    public function actionFoo() {
        // $this->pageTitle is now set automatically!
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您希望在所有操作中使用相同的标题

这很明显,但我提到它的完整性:

class MyController extends CController {
    public $pageTitle = "my title";

    public function actionIndex() {
        // $this->pageTitle is already set
    }

    public function actionFoo() {
        // $this->pageTitle is already set
    }
}
Run Code Online (Sandbox Code Playgroud)