Table of Contents
php模板引擎技术简单实现,php模板引擎
Home Backend Development PHP Tutorial Simple implementation of php template engine technology, php template engine_PHP tutorial

Simple implementation of php template engine technology, php template engine_PHP tutorial

Jul 12, 2016 am 08:57 AM
template engine

php模板引擎技术简单实现,php模板引擎

用了smarty,tp过后,也想了解了解其模板技术是怎么实现,于是写一个简单的模板类,大致就是读取模板文件->替换模板文件的内容->保存或者静态化

 

tpl.class.php主要解析

  assign 方法实现

<span>        /*</span><span>*
          * 模板赋值操作
          * @param mixed $tpl_var 如果是字符串,就作为数组索引,如果是数组,就循环赋值
          * @param mixed $tpl_value 当$tpl_var为string时的值,默认为 null
          </span><span>*/</span>
        <span>public</span> function assign($tpl_var,$tpl_value=<span>null</span><span>){
            </span><span>if</span>(is_array($tpl_var) && count($tpl_var) > <span>0</span><span>){
                </span><span>foreach</span> ($tpl_var <span>as</span> $k =><span> $v) {
                    $</span><span>this</span>->tpl_vars[$k] =<span> $v;
                }
            }elseif($tpl_var){
                $</span><span>this</span>->tpl_vars[$tpl_var] =<span> $tpl_value;
            }
        }</span>
Copy after login

fetch 方法实现

         <span>/*</span><span>*
           * 生成编译文件
           * @param string $tplFile 模板路径
           * @param string $comFile 编译路径
           * @return string
          </span><span>*/</span>
        <span>private</span><span> function fetch($tplFile,$comFile){

            </span><span>//</span><span>判断编译文件是否需要重新生成(编译文件是否存在或者模板文件修改时间大于编译文件的修改时间)</span>
            <span>if</span>(!file_exists($comFile) || filemtime($tplFile) ><span> filemtime($comFile)){
                </span><span>//</span><span>编译,此处也可以使用ob_start()进行静态化</span>
                $content = $<span>this</span>-><span>tplReplace(file_get_contents($tplFile));
                file_put_contents($comFile, $content);
            }

        }            </span>
Copy after login

简单编译方法:按照规则进行正则替换

        <span>/*</span><span>*
          * 编译文件
          * @param string $content 待编译的内容
          * @return string
          </span><span>*/</span>
        <span>private</span><span> function tplReplace($content){
            </span><span>//</span><span>转义左右定界符 正则表达式字符</span>
            $left = preg_quote($<span>this</span>->left_delimiter,<span>'</span><span>/</span><span>'</span><span>);
            $right </span>= preg_quote($<span>this</span>->right_delimiter,<span>'</span><span>/</span><span>'</span><span>);

            </span><span>//</span><span>简单模拟编译 变量</span>
            $pattern =<span> array(
                    </span><span>//例如</span><span>{$test}</span>
                    <span>'</span><span>/</span><span>'</span>.$left.<span>'</span><span>\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)</span><span>'</span>.$right.<span>'</span><span>/i</span><span>'</span><span>
                );

            $replace </span>=<span> array(
                    </span><span>'</span><span><?php echo $this->tpl_vars[\'${1}\']; ?></span><span>'</span><span>
                );

            </span><span>//</span><span>正则处理</span>
            <span>return</span><span> preg_replace($pattern, $replace, $content);
        }</span>
Copy after login

display = fetch+echo

        <span>/*</span><span>*
          * 输出内容
          * @param string $fileName 模板文件名
          </span><span>*/</span>
        <span>public</span><span> function display($fileName){
            </span><span>//</span><span>模板路径</span>
            $tplFile = $<span>this</span>->template_dir.<span>'</span><span>/</span><span>'</span><span>.$fileName;

            </span><span>//</span><span>判断模板是否存在</span>
            <span>if</span>(!<span>file_exists($tplFile)){
                $</span><span>this</span>->errorMessage = <span>'</span><span>模板文件不存在</span><span>'</span><span>;
                </span><span>return</span> <span>false</span><span>;
            }

            </span><span>//</span><span>编译后的文件</span>
            $comFile = $<span>this</span>->compile_dir.<span>'</span><span>/</span><span>'</span>.md5($fileName).<span>'</span><span>.php</span><span>'</span><span>;

            $</span><span>this</span>-><span>fetch($tplFile,$comFile);
            <br />       include $comFile;
        }</span>
Copy after login

其他属性

<span>        //</span><span>模板文件存放位置</span>
        <span>private</span> $template_dir = <span>'</span><span>templates</span><span>'</span><span>; 

        </span><span>//</span><span>编译文件存放位置</span>
        <span>private</span> $compile_dir = <span>'</span><span>compiles</span><span>'</span><span>;

        </span><span>//</span><span>左定界符</span>
        <span>private</span> $left_delimiter = <span>'</span><span>{</span><span>'</span><span>;

        </span><span>//</span><span>右定界符 </span>
        <span>private</span> $right_delimiter = <span>'</span><span>}</span><span>'</span><span>; 

        </span><span>//</span><span>内部临时变量,存储用户赋值</span>
        <span>private</span> $tpl_vars =<span> array();

        </span><span>//</span><span>错误信息</span>
        <span>private</span> $errorMessage = <span>''</span><span>;

        </span><span>/*</span><span>*
          * 修改类属性的值
          * @param array $configs 需要修改的相关属性及值
          * @return bool
          </span><span>*/</span>
        <span>public</span><span> function setConfigs(array $configs){
            </span><span>if</span>(count($configs) > <span>0</span><span>){
                </span><span>foreach</span> ($configs <span>as</span> $k =><span> $v) {
                    </span><span>if</span>(isset($<span>this</span>-><span>$k))
                        $</span><span>this</span>->$k =<span> $v;
                }
                </span><span>return</span> <span>true</span><span>;
            }
            </span><span>return</span> <span>false</span><span>;
        }</span>
Copy after login

测试

模板文件 testTpl.html

<!DOCTYPE html>
<html lang=<span>"</span><span>en</span><span>"</span>>
<head>
    <meta charset=<span>"</span><span>UTF-8</span><span>"</span>>
    <title>test_tpl_demo</title>
</head>
<body><span>
    {$name}:{$age}:{$message}
</span></body>
</html>
Copy after login

运行文件 test_tpl.php

<?<span>php
    require </span><span>'</span><span>Tpl.class.php</span><span>'</span><span>;
    
    $tpl </span>= <span>new</span><span> Tpl();
    $tplarr </span>=<span> array(
            </span><span>'</span><span>name</span><span>'</span>=><span>'</span><span>waited</span><span>'</span><span>,
            </span><span>'</span><span>age</span><span>'</span>=><span>'</span><span>100</span><span>'</span><span>
        );
    $tpl</span>-><span>assign($tplarr);
    $tpl</span>->assign(<span>'</span><span>message</span><span>'</span>,<span>'</span><span>this is a demo</span><span>'</span><span>);
    $tpl</span>->display(<span>'</span><span>testTpl.html</span><span>'</span><span>);

</span>?>
Copy after login

输出:waited:100:this is a demo

生成编译文件:972fa4d270e295005c36c1dbc7e6a56c.php

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1107665.htmlTechArticlephp模板引擎技术简单实现,php模板引擎 用了smarty,tp过后,也想了解了解其模板技术是怎么实现,于是写一个简单的模板类,大致就是读取模...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the common template engines in PHP programming? What are the common template engines in PHP programming? Jun 12, 2023 am 09:50 AM

In recent years, the template engine in PHP programming has become an important part of PHP development, making it easier for programmers to develop and manage pages. This article will introduce common template engines in PHP programming. SmartySmarty is a commonly used PHP template engine. It supports a series of functions such as cached templates, plug-in modules and custom functions. Smarty's syntax is very flexible and can solve the problem of combining PHP variables with HTML tags, making the PHP language more suitable for templated design. Moreover, S

How to use template engine Blade in Fat-Free framework? How to use template engine Blade in Fat-Free framework? Jun 03, 2023 pm 08:40 PM

Fat-Free Framework is a lightweight PHP framework designed to provide simple and flexible tools for building web applications. It contains many useful features such as routing, database access, caching, etc. In the Fat-Free framework, using the Blade template engine can help us manage and render templates more conveniently. Blade is the template engine in the Laravel framework, which provides powerful syntax and template inheritance capabilities. In this article I will demonstrate how to use Bl in Fat-Free framework

ThinkPHP6 template engine usage guide: Create an exquisite front-end interface ThinkPHP6 template engine usage guide: Create an exquisite front-end interface Aug 26, 2023 pm 11:09 PM

ThinkPHP6 template engine usage guide: Create an exquisite front-end interface Introduction: With the development of web applications, the design and development of front-end interfaces have become increasingly important. As a developer, we need to use a powerful template engine to help us create and manage front-end interfaces. ThinkPHP6's template engine is a powerful tool to meet this need. This article will introduce how to use the ThinkPHP6 template engine to create a beautiful front-end interface. Part 1: Install ThinkPHP6 template engine

Learn to use the Golang template engine: A basic guide to using templates in Golang Learn to use the Golang template engine: A basic guide to using templates in Golang Jan 20, 2024 am 10:13 AM

Golang Template Engine Getting Started Guide: How to use templates in Golang, specific code examples are required Introduction: A template engine is a tool that can combine data and templates and generate documents in HTML, text or other formats. In Golang, we can use the built-in template package (html/template) to implement the functions of the template engine. This article will introduce in detail how to use the template engine in Golang and provide specific code examples. 1. The basic concept of template engine is to understand how to use it.

Template Engine in Go: A Complete Guide Template Engine in Go: A Complete Guide Jun 17, 2023 pm 12:55 PM

With the development of Internet technology, the demand for web applications is also increasing. Web developers often use template engines to generate dynamic web pages. This article will explore a new template engine: the Go language template engine. What is the Go language template engine? Go language is an advanced programming language developed by Google. Its syntax is concise and clear, making it easy to learn and use. The Go language template engine is a template system used to generate HTML templates in the Go language. The Go language template engine is called the "standard library".

Template engine selection and usage experience sharing in JavaScript development Template engine selection and usage experience sharing in JavaScript development Nov 04, 2023 am 11:42 AM

Sharing experience on template engine selection and use in JavaScript development Introduction: In modern front-end development, the template engine (TemplateEngine) plays a crucial role. They enable developers to organize and manage large amounts of dynamic data more efficiently and effectively separate data from interface presentation. At the same time, choosing an appropriate template engine can also bring developers a better development experience and performance optimization. However, among the many JavaScript template engines, which one should you choose? catch

Template engines for PHP and CGI: How to achieve website reusability Template engines for PHP and CGI: How to achieve website reusability Jul 20, 2023 pm 10:13 PM

PHP and CGI template engines: How to achieve website reusability Introduction: When developing websites, we often need to deal with the display of dynamic content. In order to achieve code maintainability and reusability, using a template engine is a wise choice. This article will introduce PHP and CGI, two commonly used template engines, and show how to use them to achieve website reusability through code examples. 1. PHP template engine PHP is a widely used server scripting language with flexibility and powerful functions. PHP template engine is a

Best Template Engine in PHP Best Template Engine in PHP May 24, 2023 pm 04:01 PM

PHP is a language widely used in web development. Whether you are developing a small website or a large system, PHP is very popular and convenient. In the PHP development process, we need to separate the logic and data layers, which requires the use of a template engine. The template engine can be simply understood as merging data and template files to generate the final HTML file. In this article, we will introduce some of the best template engines available in PHP. SmartySmarty is one of the most popular template engines in PHP,

See all articles