Today, let's talk about how to build your own PHP template engine. Currently, the popular PHP template engines include Twig, Haml, Liquid, Mustache, Plates, Blade, and the older Smarty. In fact, PHP should not use the template engine. There are also a lot of debates on the Internet, here are some advantages of using the template engine.
Security, such as default escape output
Good readability
For more information, see Zhihu.
What is the significance of the PHP template engine?
Why does ThinkPHP have something similar to the template engine in PHP? So is smarty? How can this be used?
First, let's determine the method of writing in the template. refer to the Blade template of Laravel and define the following simple methods.
Output variable value
The return value of the {} expression is automatically passed to the htmlentities function of PHP for processing to prevent XSS attacks.
Hello, {{ $name }}!
Output unescaped variable values
Hello, {!! $name !!}!
If expression
You can use the @ if, @ elseif, @ else, and @ endif commands to create an if expression.
@if (count($records) === 1) I have one record!@elseif (count($records) > 1) I have multiple records!@else I don't have any records!@endif
Loop
@for ($i = 0; $i < 10; $i++) The current value is {{ $i }}@endfor@foreach ($users as $user) This is user {{ $user->id }}
@endforeach@while (true) I'm looping forever.
@endwhile
Introduce other views
@include('view.name', ['some' => 'data'])
It is enough to define so much for the moment. If you have special requirements, you can add them by yourself. The principle is basically the same. you can write one file and write all the other files.
Then let's think about how to deal with it. we have defined such a writing method that PHP cannot recognize. we need to convert it into what PHP can recognize.
For example, when we get a piece of content such as {$ name}, we only need to convert it In this way, you can identify and output the corresponding variable values.