Home  >  Article  >  Backend Development  >  ThinkPHP template engine implementation and common problems

ThinkPHP template engine implementation and common problems

云罗郡主
云罗郡主Original
2019-01-07 09:37:003243browse

Origin of template engine

In the early days of developing WEB applications in PHP, PHP code and HTML templates were mixed together. The birth of the template engine was mainly to solve the complete separation of the back-end and the front-end. (Now it seems that it is actually an incomplete separation) problem, so that development and artists can divide and cooperate (although in fact, most of the final template work is still completed by back-end developers), thereby improving development efficiency and facilitating maintenance.

With the rapid growth of PHP, there are more and more template engines, but they are roughly divided into two types: interpreted and compiled. Most of the current mainstream template engines are compiled, that is, they will first The template is compiled into a PHP file for execution. As long as the template file itself does not change, there is no need to recompile, such as the old Smarty. An interpreted template engine will perform a template parsing process every time it is executed, such as tinybutstrong.

ThinkPHP has built-in a compiled template engine based on XML tag library technology from the beginning. It was early referenced from Struts and is constantly evolving by absorbing new ideas.

How to choose a template engine

Currently mainstream frameworks come with template engine components or encapsulate the implementation of template engines, so choosing a built-in solution is the best choice. , functionality and stability are guaranteed. Currently, the most popular template engines are Laravel's own Blade template engine and Symfony's own Twig template engine.

By installing the template engine extension, you can easily use template engines including Angular, Twig and Blade in ThinkPHP, or even use PHP files directly as templates without using a template engine at all.

Due to the popularity of the three major front-end frameworks (React/Vue/Angular) in recent years, separate development of front-end and back-end has gradually become mainstream. Therefore, ThinkPHP5.0 has been positioned for API development, leading to the concept of template engine. has been weakened. The template engine of ThinkPHP version 5.1 has undergone an internal reconstruction, making template tags easier to use and closer to PHP syntax.

At least for most new applications, you should choose a more mainstream front-end and back-end separation design to reduce the pressure on the server as much as possible and make it easier to test the front and back ends separately. You will inadvertently see products using Vue and ThinkPHP on the market (previous issues of ThinkPHP Developer Weekly have reported on several). If you are maintaining some old projects, especially content management products, you may still use template engines.

In view of this situation, the next version of the ThinkPHP framework will not have a built-in template engine, but developers who need to use the template engine can still use the official independent think-template class library. For specific usage, please refer to This article.

In the following sections, we will mainly summarize the use and techniques of ThinkPHP's built-in template engine.

Template execution process

The template engine calling relationship within the system is as follows:

视图(View) <=> 模板驱动(Driver) <=> 模板引擎(Template)

A driver layer is added between the view and the template engine, so It can be easily replaced by other template engines. Usually, the assign/fetch and other methods we call in the controller are actually the methods of the think\View class called. Of course, if necessary, you can also directly operate the template engine class in the controller, but it is not convenient to switch to other template engines.

Taking the fetch method as an example, let’s take a look at the final calling process:

think\Controller->fetch();
think\View->fetch();
think\view\driver\Think->fetch();
think\Template->fetch();

If you do not pass in the complete template file name to be rendered when calling the fetch method, it will be displayed in the third Automatically identify the template file to be rendered during step.

Obviously, the most critical step is the last step. The process of template compilation and execution is all completed by the

think\Template->fetch();

method. This link can be roughly divided into several processes.

1. Determine and read the page rendering cache

If the current template sets the page output cache and has been rendered and output, if so, the output content in the cache will be read and output directly.

if (!empty($this->config[&#39;cache_id&#39;]) && $this->config[&#39;display_cache&#39;])
 {
    // 读取渲染缓存
    $cacheContent = $cache->get($this->config[&#39;cache_id&#39;]);

    if (false !== $cacheContent) {
        echo $cacheContent;
        return;
    }
}

2. Locate the template file

The actual template file positioning operation is implemented by the parseTemplateFile method of the template engine class. The logic of this method is actually similar to the parseTemplate method of the view driver class. If If the final template file does not exist, a template file does not exist exception will be thrown.

$template = $this->parseTemplateFile($template);

3. Determine the compilation cache

If the current template file has been compiled, it will be judged whether the cache is still valid. If it is valid, there is no need to repeat the parsing and directly read the cached parsing content. This is done by the checkCache method.

if (!$this->checkCache($cacheFile)) {
    // 缓存无效 重新模板编译
    $content = file_get_contents($template);
    $this->compiler($content, $cacheFile);
}

4. Template compilation and caching

This step is the core link of the template engine and the most complex function. It is completed by the compiler method, which mainly parses the current template file. The template tag syntax is PHP executable code, and then a template parsing cache file is generated, which is the so-called template "compilation", which uses a lot of regular expression replacement technology. Although regular expression parsing has a certain performance overhead, but the benefits Based on the caching principle of parsing multiple calls once, basically the performance overhead of template parsing will not affect the actual performance.

The key code of the template compilation method is the parse method. The parse method is responsible for parsing the tags in the template file and then writing it to the compilation cache file. The compilation cache uses the file cache by default and supports expansion.

5. Read the compilation cache

模板编译的过程只是生成了模板编译缓存文件,并没有真正载入模板,这一步骤就是载入模板编译缓存,然后导入模板变量。实现方法可以参考think\template\driver\File类的read方法。

public function read($cacheFile, $vars = []){
    $this->cacheFile = $cacheFile;

    if (!empty($vars) && is_array($vars)) {
        // 模板阵列变量分解成为独立变量
        extract($vars, EXTR_OVERWRITE);
    }

    //载入模版缓存文件
    include $this->cacheFile;
}

6、缓存页面输出

如果当前模板渲染的时候开启了页面输出缓存,就会这一步生成页面渲染后的输出缓存。

模板编译原理

我们来了解下ThinkPHP的模板引擎的实现原理。前面提到过,ThinkPHP的模板引擎最早源于Struts的设计理念,基于XML和标签库的技术实现。在设计模板语言的时候使用系统固定的标签来实现普通的变量输出功能(所以称之为普通标签),而利用XML标签库技术实现的动态标签用于变量的控制或者条件判断输出。

普通标签的解析是由think\Template类的parseTag方法完成的,主要实现了下面几个模板功能:

变量输出(包括系统变量);

函数过滤;

变量运算;

三元运算;

执行函数以及输出结果;

模板注释;

标签库采用的是动态扩展的设计方案,采用了类似XML的闭合/开放定义方式(这个其实也是目前模板引擎的一个局限所在),例如下面的这个:

// 闭合类型标签
<tagLib:tagName name="value" >...</tagLib:tagName>
// 开放类型标签
<tagLib:tagName name="value" />

tagLib就代表了一个标签库(类),后面的tagName标签就表示该标签库下面的某个标签(通常对应了标签库类的某个方法),后面的属性就是该标签支持的属性定义。具体该标签的属性和功能则完全由标签库类的这个方法来决定。

可以在模板开头明确指出,当前模板使用了哪些标签库

{taglib name="html,article" /}

所以要扩展模板引擎的功能只需要通过扩展一个标签库类就可以了。大多数的内容管理系统都会定义一套自己的模板二次开发标签,利用标签库功能就可以很方便的定义一套属于自己的标签功能。

系统内置了一套标签库Cx,主要用于文件包含、条件控制、循环输出等功能。内置标签库在使用的时候无需引入,而且在使用的时候可以省略标签库前缀,例如:

{foreach $list as $key=>$vo } 
    {$vo.id}:{$vo.name}{/foreach}

这个模板语法相信PHP开发的很容易上手,上面的标签解析由think\template\taglib\Cx类的tagForeach方法完成,该方法的返回值是一个字符串,其实就是最终会解析成的一段包含变量的PHP可执行代码。

到这里,模板引擎的执行过程和原理现在基本就明白了,剩下的就是模板标签的解析细节,考验的就是正则表达式的掌握程度了。本文就不做深入了,有兴趣的朋友可以去看一些正则表达式的相关资料(例如这本《正则指引》,开发者周刊第14期也提供了一些在线的正则工具)。

遵循的原则

使用模板引擎,要尽量遵循几个重要的原则。

不要在模板文件中添加任何的业务逻辑

模板的作用主要是进行模板变量的控制和输出,不要在模板文件中添加业务逻辑代码。

明确指定渲染模板

养成明确指定渲染模板的好习惯,避免当方法名发生变化,或者被其它方法调用的时候发生错误。也不易受模板命名规范的影响。

变量统一赋值

使用assign方法或者在view助手函数的时候,统一一次传入模板变量。不要多次赋值,以免混乱。

系统变量无需赋值到模板

对于系统变量(包括请求变量、$_SESSION和$_SERVER等系统变量)无需进行模板变量赋值,可以直接在模板中输出。

常见问题

这里总结一下经常会遇到的一些常见问题。

修改定界符

可以通过模板配置文件修改模板标签的定界符。

例如,修改普通标签定界符

&#39;tpl_begin&#39;          => &#39;{{&#39;, // 模板引擎普通标签开始标记
&#39;tpl_end&#39;            => &#39;}}&#39;, // 模板引擎普通标签结束标记

标签库标签定界符

&#39;taglib_begin&#39;       => &#39;<{&#39;, // 标签库标签开始标记
&#39;taglib_end&#39;         => &#39;}>&#39;, // 标签库标签结束标记

保持原样输出

如果担心模板标签和JS代码产生混淆,可以使用literal标签

{literal} Hello,{$name}! {/literal}

页面最终会直接输出Hello,{$name}!

避免输出转义

5.1版本为了避免XSS攻击,默认对模板变量的输出使用了安全转义,默认的转义函数是htmlentities,你可以通过更改default_filter配置改变默认的转义函数。

如果你不需要对某个模板变量输出进行转义(例如包含了HTML代码),可以使用:

{$data.content|raw}

分页输出就是一个需要输出HTML的典型例子,因此必须增加|raw。

关于模板主题

新版取消了原来的模板主题功能,因为模板主题对模板引擎来说,其实无非是一个模板目录,完全可以根据自己的需求控制。

例如

$theme = &#39;blue&#39;;$this->fetch(&#39;/&#39; . $theme. &#39;/user/index&#39;);

或者动态设置模板引擎的view_path参数

$this->view->config(&#39;view_path&#39;, \think\facade\App::getModulePath(). &#39;view/&#39;. $theme . &#39;/&#39;);

如何关闭模板缓存

由于是编译型模板引擎,模板标签不能被直接执行,必须编译成PHP语法后才能执行,因此不能关闭模板编译缓存,模板引擎每次执行渲染的时候会检测模板文件是否有变化,当模板文件的修改时间超过模板编译缓存的修改时间后,模板引擎会自动更新编译缓存。

但你可以强制模板引擎每次都重新编译,只需要在配置文件中设置

&#39;tpl_cache&#39;          => false, // 关闭模板缓存

使用PHP作为模板引擎

如果不希望使用内置的模板引擎,直接使用PHP作为模板引擎,可以配置

 &#39;type&#39;         => &#39;php&#39;,

配置使用PHP作为模板引擎的话,是不会生成模板编译缓存的。

如何使用第三方模板引擎

系统支持扩展其它的第三方模板引擎,你只需要开发一个模板引擎驱动,目前已经支持的第三方模板引擎包括Smarty、Twig和Blade。

如何跨模块输出模板

要渲染一个跨模块的模板文件,你需要使用

// 渲染user模块的模板文件

$this->fetch(&#39;User@order/index&#39;);

是否支持变量运算

可以直接在模板文件中进行变量运算而不需要在控制器中进行运算后再赋值都模板变量输出。

{$score1+$score2}
{$count++}

文件包含是否支持变量

include标签可以支持传入变量,但只能使用

{include file="$file" /}

而不能使用

{include file="file_$name" /}

可以支持模板输出替换么

支持两个方式对模板进行输出替换,如果需要对模板文件的内容进行替换,可以配置:

&#39;tpl_replace_string&#39;  =>  [
    &#39;__STATIC__&#39;=>&#39;/static&#39;,
&#39;__JS__&#39; => &#39;/static/javascript&#39;,
]

如果是对模板渲染输出的内容进行替换,可以在控制器中使用视图过滤功能:

public function index(){
    // 使用视图输出过滤
    return $this->filter(function($content){
    return str_replace("\r\n",&#39;<br/>&#39;,$content);
    })->fetch();
}

模板继承的block是否支持嵌套

目前模板继承的block无法支持嵌套功能,你应该使用其它方式解决。





The above is the detailed content of ThinkPHP template engine implementation and common problems. For more information, please follow other related articles on the PHP Chinese website!

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