Template in the CakePHP 4 is a .php file where define the HTML layout of the page. Template files automatically get loaded on the page. For this need to create files in a specific pattern.
From Controller, you can pass data to the template file.
In this tutorial, I show how you can create template files and pass values from the controller to the template in CakePHP 4 project.
Contents
1. Create Controller
Create a HomeController.php
file in src/Controller/
folder.
Create HomeController
Class that extends AppController
.
In the class create 2 methods –
- index() – Assign a string value to
$page
and$content
variables. To pass this value to the template use$this->set()
. It takes an Array value.compact()
function converts passed variable names to an Array in which the key is same as the variable name. - aboutus() – Assign a string value to
$page
variable. Initialize$data['page']
with$page
. Pass$data
to$this->set()
. In the template file reading the value is the same as the above-specified way.
CakePHP automatically converts the method names as a request parameter.
This will create the following requests –
- index – http://localhost:8765/home or http://localhost:8765/home/index
- aboutus – http://localhost:8765/home/aboutus
Completed Code
<?php declare(strict_types=1); namespace App\Controller; class HomeController extends AppController { public function index(){ $page = "Homepage"; $content = "Welcome to Makitweb"; // Pass value to template $this->set(compact('page','content')); } public function aboutus(){ $page = "About US"; // Pass value to template $data['page'] = $page; $this->set($data); } }
2. Create Template
Create a new Home
folder in templates/
folder. Now in the Home
folder create index.php
and aboutus.php
file.
Here, make sure the folder name is the same as the controller name – Home
and the file name is the same as the method names created in the controller – index()
, and aboutus()
.
templates/Home/index.php
In the page just create a <h1 >
and <p >
tag. You can either read the values passed from the controller using <?php echo $page ?>
or <?= $page ?>
.
Completed Code
<h1><?= $page ?></h1> <p><?= $content ?></p>
templates/Home/aboutus.php
In this file also create <h1>
and <p>
tags. I displayed static value in the <p >
tag and display passed value in <h1 >
tag – <?= $page ?>
.
Completed Code
<h1><?= $page ?></h1> <p>About us page content</p>
4. Output
Home page (http://localhost:8765/home/index)
About us page (http://localhost:8765/home/aboutus)
5. Conclusion
You don’t need to call template files explicitly from the controller. So the naming of the files and folder is important while creating a template.
If you found this tutorial helpful then don't forget to share.