How to create a legacy template engine in PHP

Tram Ho

Until now, when using the framework, I really like the inheritance of view engine. It helps me a lot in the layout division, the code feels coherent and convenient. Curious and explored, today I would like to share with everyone how to create a super “smart” template engine that is simple for you guys. Let’s go

Initialization

First, let’s create a project with the following structure:


➡️


➡️


➡️

Well, the project is simply a template.php file.

Well the above code is just initializing the template.php class file, I have carefully explained the variables and methods in the Template class. The following will code in detail each function.


Code

The constructor


Next comes the include function . This function is also quite simple, but you need to have a good understanding of output buffering . You can consult about buffers at php.net

Section and end functions. We will get the HTML (XML) code between the section and the end function

The layout and renderSection functions are even simpler.

Finally the function renders a view. This function will call the section and end functions first, then inherit the layout, and finally return a string of complete HTML (XML) file.

ok. that’s done with the code template engine. Now try it out.

Call Template Engine

First we create a file ~/views/layout.php .

Note: in this template engine, I use the view file extension .php . You can customize this file extension in the __resolvePath function template.php file above

Next we create a file view ~/views/profile.php

In the file index.php (the file you need to call that view).

Ok. You try the ~/index.php file and enjoy the results.

summary

Creating a template engine by yourself is not difficult, it is important that you understand the output buffering in PHP.  https://www.php.net/manual/en/ref.outcontrol.php

Share the news now

Source : Viblo