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

Build PHP framework and build template engine

高洛峰
Release: 2016-10-31 14:32:25
Original
1030 people have browsed it

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 }}!
Copy after login

Output unescaped variable values ​​

Hello, {!! $name !!}!
Copy after login

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
Copy after login

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
Copy after login

Introducing other views

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

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.


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template