Home > Article > Backend Development > Build PHP framework and build template engine
In fact, there are a lot of debates on the Internet about whether PHP should use template engines. Here are some advantages of using template engines.
Safe, such as default escape output
Good readability
For related content, you can refer to Zhihu’s discussion
How meaningful is the PHP template engine?
Why does ThinkPHP do something similar to a template engine in PHP? Smarty too? What are these used for?
First of all, let’s determine the idea. We first need to determine what writing method to use in the template. Refer to Laravel’s Blade template and define the following simple writing methods.
Output variable value
{{ }} The return value of the expression will be automatically passed to PHP's htmlentities function for processing to prevent XSS attacks.
Hello, {{ $name }}!
Output unescaped variable values
Hello, {!! $name !!}!
If expressions
If expressions can be created using the @if, @elseif, @else and @endif directives.
@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) <p>This is user {{ $user->id }}</p>@endforeach@while (true) <p>I'm looping forever.</p>@endwhile
Introducing other views
@include('view.name', ['some' => 'data'])
Defining so many for now is basically enough. If you have special needs, you can add them yourself. The principles are basically the same. If you can write one, you can write the others.
Then consider how to deal with it. We have defined such a way of writing that PHP cannot recognize it. We need to convert it into something that PHP can recognize.
For the simplest example, when we get a piece of content like {{ $name }}, we only need to convert it into In this way, we can identify it and output the corresponding variable value.