Templates
A template is a file with HTML markup into which data from the controller is inserted. CakePHP templates are written in plain PHP; there is no separate template language.
Where they live
Templates are in the templates folder in the project root. Every controller has its own subfolder and every action its own file:
| Action | Template file |
|---|---|
ArticlesController::index() | templates/Articles/index.php |
ArticlesController::view() | templates/Articles/view.php |
ArticlesController::add() | templates/Articles/add.php |
The files are created by hand, or with bin/cake bake template Articles once the table exists in the database.
A simple template
The action passes a variable:
// src/Controller/ArticlesController.php
public function index(): void
{
$this->set('title', 'Articles');
}The templates/Articles/index.php template outputs it:
<h1><?= h($title) ?></h1><?= ... ?> is a short form of echo. The heading "Articles" appears at /articles.
Escaping
The h() function replaces markup characters with safe ones: < becomes <. Text that contains a tag is shown on the page as text and is not executed:
<p><?= h($comment) ?></p>Everything that came from a visitor or from the database is output through h().
A list
Pass an array from the action:
$this->set('articles', ['First article', 'Second article']);<ul>
<?php foreach ($articles as $article): ?>
<li><?= h($article) ?></li>
<?php endforeach; ?>
</ul>Templates use the loop syntax with a colon and endforeach, which is easier to read among tags. The page shows a list of two items.
A condition
<div>
<?php if (empty($articles)): ?>
<p>No articles yet.</p>
<?php else: ?>
<p>Articles: <?= count($articles) ?></p>
<?php endif; ?>
</div>With an empty array the visitor sees "No articles yet."
Another template
An action can render a template with a different name:
public function latest()
{
$this->set('articles', ['Fresh article']);
return $this->render('index');
}render('index') takes templates/Articles/index.php instead of latest.php, so two actions share one template.
Common mistake
<?= $title ?> without h() outputs the value as is: if an article title contains a <script> tag, it runs in the browser of every visitor. CakePHP does not escape output by itself, so wrap every value in h().