Home  >  Article  >  Backend Development  >  Build PHP framework and build template engine

Build PHP framework and build template engine

高洛峰
高洛峰Original
2016-10-31 14:32:251011browse

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&#39;m looping forever.</p>@endwhile

Introducing other views

@include(&#39;view.name&#39;, [&#39;some&#39; => &#39;data&#39;])

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.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn