$this->set('title', 'Title Name'); not working in CakePHP 3.x

Tachi picture Tachi · May 11, 2015 · Viewed 17k times · Source

Basically in default.ctp I have this for my title:

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

And inside of the controller I have this line:

$this->set('title', 'Test-Title');

But it does nothing, it still displays controllers name(Jobs, controllers full name os JobsController.ctp)

But if I put this inside of my view file:

$this->assign('title', 'Test-Title');

It changes the title. So what is wrong with $this->set('title', $title) ?

Answer

drmonkeyninja picture drmonkeyninja · May 11, 2015

fetch() returns the contents of a block not a variable. Using set() in your Controller is setting a variable that can be output in your View templates by echoing the variable:-

<?php echo $title; ?>

If you want to use fetch() you need to use it in combination with assign() in the View templates to define the block. For example in your View template use:-

<?php $this->assign('title', $title); ?>

And then in the layout template:-

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

In CakePHP 3 the idea is to set the page title by assigning it in the View as it relates to the rendering of the page. This differs from how this was originally handled in CakePHP 2 where you'd define title_for_layout in your controller and then echo the $title_for_layout variable in the layout template (this was deprecated in favour of the CakePHP 3 approach in later versions of Cake 2).