How to reuse common parts in a view with CakePHP

Hello.
This is Hase from the development team.
I often develop using CakePHP, and
when writing views, I've always
written common parts like the `<head>` section, `<header>`, and `<footer>` into separate files.
However, writing it this way means that if corrections are needed,
you have to modify each file individually, which is very difficult and troublesome.
This led me to wonder if there was any way to group the common parts together, so I did some research and
found a method, which I'd like to share.
method
1. Create a common layout view file under app/View/Elements/
First, create a common layout under app/View/Elements/.
The file name will be {any file name}.ctp, just like a regular View.
Let's call them head.ctp, header.ctp, and footer.ctp this time.
You can simply copy and paste the head, header, and footer sections that you would normally write in your View into these files.
Incidentally, it's also possible to create a directory under `app/View/Elements/` and place the View file there.
For example: `app/View/Elements/Admin/header.ctp`
2. Load the file you just created in a normal view
In the part you want to load
// Common head<?php echo $this-> element('head'); ?> // Common header<?php echo $this-> element('header'); ?> // Common footer<?php echo $this-> element('head');
This will automatically load the file you just created
Also, if you have created a directory like app/View/Elements/Admin/
// Common head<?php echo $this-> element('Admin/head'); ?> // Common header<?php echo $this-> element('Admin/header'); ?> // Common footer<?php echo $this-> element('Admin/head'); ?>
It is OK if you write it like this
Problem
Even common elements often differ in certain parts.
A common example is the title tag within the head section.
The content of the title tag element often varies from page to page.
This situation can also be handled
to $this->element() by using an associative array as the second argument, in the format ["variable name" => "value"]
You can pass parameters
Usage example:
// Element side (head.ctp)<head> .......<title> <?php echo $title; ?></title></head>
// Normal View side (caller)<?php echo $this-> element('head', ["title" => "Top"]); ?>
It's very convenient because you can call it like this
That's all
3
