Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) ?

like image 743
Tachi Avatar asked May 11 '15 14:05

Tachi


3 Answers

In CakePHP 3 layout template, make sure to set the title as below.

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

Then in your view:

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

This is the way CakePHP will use its built-in View classes for handling page title (view blocks) rendering scenarios.

like image 191
Chinthaka Hettiarachchi Avatar answered Oct 06 '22 12:10

Chinthaka Hettiarachchi


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).

like image 33
drmonkeyninja Avatar answered Oct 06 '22 12:10

drmonkeyninja


You can just set() the variable in your controller:

// View or Controller
$this->set('title', 'Test-title');

Then use it as a standard variable is in your layout or view:

<!-- Layout or View -->
<title>
    <?php echo $title; ?>
</title>

Details here: http://book.cakephp.org/3.0/en/views.html#setting-view-variables

Using assign() is different, which is why it works with fetch(). assign() is used with View Blocks: http://book.cakephp.org/3.0/en/views.html#using-view-blocks

like image 38
Dave Avatar answered Oct 06 '22 14:10

Dave