How to reuse common parts in a view with CakePHP

Hello,
this is Hase from the development team.

I often develop using CakePHP, and
until now when writing views,
I have been writing common parts such as the head, header, and footer in separate files.

However, if you write it like this, when you need to make any changes
, you will have to edit each file one by one, which is very difficult and tedious.

Because of this, I wondered if there was a way to somehow group the common parts together, and after doing some research, I
found a way, which I would like to introduce.

method

1. Create a common layout view file under app/View/Elements/

First, create a common layout under app/View/Elements/.
The file name is {any file name}.ctp, just like a normal View.

Let's call them head.ctp, header.ctp, and footer.ctp this time.
Just copy and paste the head, header, and footer parts that you wrote in the normal View.

By the way, you can also create a directory under app/View/Elements/ and place the view file under it.
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 though they are common parts, there are often some differences.
A common example is the title tag in the head.
The content of the title tag element often differs depending on the page.

This situation can also be handled


You can pass parameters to $this->element() by using an associative array as the second argument, ["variable name" => "value"]

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 useful, please click [Like]!
3
Loading...
3 votes, average: 1.00 / 13
8,919
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 working in the Osaka office, he was transferred to the Yokohama office in 2019.
His hobbies are baseball, karaoke, and anime.