How can I set the title_for_layout in the default PagesController?

廉价感情. 提交于 2019-12-09 18:29:52

问题


I cannot set title_for_layout in the PagesController that comes by default with CakePHP 1.3.

I am using the following code in the display function:

$this->set('title_for_layout','some title');

What am I doing wrong?


回答1:


In your controller, the corresponding value is $this->pageTitle.

UPDATE

Oops, as noted in the comments, this is the 1.2 solution. 1.3 possibilities (after doing some research) include:

  1. Ensuring that $title_for_layout is being echoed in the layout
  2. Placing the $this->set() code in the view rather than in the controller



回答2:


If you'd like to mimic the behavior of cake 1.2, you can do the following:

In your app_controller, create the following method:

in app/app_controller.php (you may need to create this file if you haven't already)

public $pageTitle;

public function beforeRender() {
    $this->set('title_for_layout', $this->pageTitle);
}

Then in any of your action methods, you may then use the pageTitle as you would in 1.2.

public function index() {
    $this->pageTitle = 'Some Title';
}

The beforeRender() method will be called after your controllers have finished processing, but prior to the layout being rendered, thus allowing you to set variables for the layout.




回答3:


In the action method, try this:

function index()
{
    $this->pageTitle= 'Your Title';
}



回答4:


Just thought I'd add to any new people finding this solution, you can do $this->set('title', $title); in CakePHP 1.3 inside the controller and the title will be rendered automatically.




回答5:


You can use :

$this->assign('title', 'Some title');

and in ctp :

<title><?= $this->fetch('title'); ?></title>

It work in CakePHP 3.0




回答6:


For CakePHP 3.x,

you can follow the advice here

Essentially,

Inside UsersController.php:

$this->set('title', 'Login');

Inside src/Template/Layouts/default.ctp

above the $this->fetch('title');

write:

if (isset($title)) {
    $this->assign('title', $title); 
}



回答7:


Use beforeRender() instead. Put the following in AppController:

class AppController extends Controller {
    var $content;

    function beforeRender() {
        $this->set('content',$this->content);
    }            
}

And in the controller, you can just do:

function index() {
    $this->content['title'] = '123'; }

That'll do the trick.



来源:https://stackoverflow.com/questions/2628963/how-can-i-set-the-title-for-layout-in-the-default-pagescontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!