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

If you found this article helpful,please give it a "Like"!
3
Loading...
3 votes, average: 1.00 / 13
8,977
X Facebook Hatena Bookmark pocket

The person who wrote this article

About the author

Tatsuya Hase

Joined Beyond Co., Ltd. as a new graduate

We develop web systems (development of browser-based services and systems such as web services, digital content, and business management systems) and game APIs (development of programs for communication with app games)

We also develop private/custom apps for Shopify

Originally worked at the Osaka office, but transferred to the Yokohama office in 2019.
Hobbies: baseball, karaoke, anime.