CakePHP3 How to use partial template like in Rails


Now I will explain how to use partial template in CakePHP 3, which is created like Rails. The Japanese document of CakePHP 3 is not up to date, but English document is.

Environment

  • PHP 5.5.9
  • CakePHP 3.0.9

Partial Template in Rails

In rails, for example, rails g scaffold xxxx generates the file _form.html.erb. It is the partial template. The head of the file name is _, and it is called in new.html.erb in the following way.

Now, how do we use such a partial template in CakePHP 3 ?

Partial Template in CakePHP 3

We use Element in CakePHP 3. Simple explanation of Element is written as the following, in CakePHP 3 document.

elements: small, reusable bits of view code. Elements are usually rendered inside views.

Create element file and call it in template file.

Element

Element file should be located in the directory src/Template/Element/. When you create element in the plugin directory, create directory src/Template/Element/ in the plugin directory and locate element in it. For example, create element as src/Template/Element/form.ctp.

And call it in template (.ctp), like the following code.

Divide in directories

rails g scaffold xxxx locate the partial template, _form.html.erb, into the related directory. Now in CakePHP 3, let’s divide elements into directories.

Create directory freely, and locate element freely, and call it like the following.

Element in Plugin

When we create element in plugin directory, that element can be called like above code from templates in the same plugin. From outside of the plugin, it can be called like the following.

Caching is another feature of the element. If you want to know more, please read CakePHP 3 documents.