Table of Contents
Articles you may be interested in
Home Backend Development PHP Tutorial smarty template execution principle_PHP tutorial

smarty template execution principle_PHP tutorial

Jul 13, 2016 am 10:31 AM
smarty principle implement template

In order to separate the business logic of the program from the content presentation page and improve the development speed, PHP introduced the concept of template engine. The most popular PHP template engine can be said to be smarty. Smarty is powerful and powerful. It is fast and recognized by the majority of PHP web developers. This article will record the working execution principle of smarty template engine to deepen our understanding.

In fact, the working principle of all template engines is similar. It is nothing more than using regular matching in the PHP program to replace the tags in the template with PHP code to mix the two into a PHP mixed file, and then execute this mixed file. Compile documents. That's basically what happened. Let’s take smarty as an example to describe this process.

For example, the article page of this website: http://www.phpernote.com/article.php?id=795

The general process is as follows:

Part of the html template page code (article.html):

<body>
<div>{subject}</div>
<div>{content}</div>
</body>
Copy after login

PHP page logic part code:

$subject='smarty视频教程分享';
$content='smarty视频教程分享,下面是具体的下载地址,有需要的朋友可以看看,对smarty模板讲解的非常详细,作者粗略看了一下目录,真是详细到细枝末节该......';
$str=file_get_contents('article.html');
$str=str_replace('{subject}',$subject,$str);
$str=str_replace('{content}',$content,$str);
echo $str;
Copy after login

The encapsulation code using object-oriented technology to implement the template function is as follows:

<?php
class Template{
	//属性
	public $vars;                        //保存要替换的标记和数据的内容
	public $left_delimiter='{*';        //左分隔符
	public $right_delimiter='*}';        //右分隔符
	//方法
	public function assign($key,$value){
		$this->vars[$key]=$value;
	}
	public function display($file){//file表示模板名
		$str=file_get_contents($file);//从模板中读取多有内容,并将内容放入$str中
		foreach ($this->vars as $key => $value){ //$key 键名(模板标记) $value 值
			$str=str_replace($this->left_delimiter.$key.$this->right_delimiter, $value, $str);
		}
		echo $str;
		//file_put_contents('bak.html', $str);
	}
}
Copy after login

Note: assign('name','zhangsan'); in this sentence, the data has not been replaced yet, but the incoming data is saved in vars[], and is only performed when displaying Data replacement.

smarty processing process:

1. Smarty first compiles the php source file into an intermediate file

2. If caching is enabled, the cache file will be generated based on the compiled file

3. Each subsequent access will access the compiled file

If the cache file is enabled and there is a cache file and the cache file has not expired, access the cache file directly (ignoring the caching process first) In the compiled file The timestamp records the modification time of the template file. If the template has been modified, it can be detected and recompiled.

(Compilation is to save static content, and dynamic content varies according to the parameters passed in)

Reading compiled files saves the time of reading template files and string replacement, so it can be faster.

Compile when article.php is requested for the first time, and a compiled file is generated, which is in the compiled file.

When requesting article.php for the second time, determine whether the template file has changed. If the template file has changed, then read the template file and then compile it. If it has not changed, read the compiled file. The final output of the compiled file;

Caching is turned off by default; caching is to store data completely in the cache file, and it will not be cached again until the cache file expires; therefore, smarty is not particularly suitable for some websites that are particularly real-time;

The above text can be understood abstractly as the picture below. Readers can experience it for themselves!

smarty template execution principle_PHP tutorial

Consider caching:

In the smarty program, to determine whether the cache file is enabled and the cache file has not expired, go to the cache file. If the cache file is not enabled, go to the template file. If The cache file has expired, and the template file is also judged.

Articles you may be interested in

  • The loop table in smarty template is not fully supplemented with td
  • Extension plug-in for for loop in smarty template
  • How to generate random numbers in smarty templates
  • How to determine if an array is empty in smarty templates
  • How to use constants defined by define in the program in smarty templates
  • Using php functions in smarty templates and how to use multiple functions for one variable in smarty templates
  • Add the latest tags to information in smarty templates
  • Summary of retained variables in smarty templates

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/764079.htmlTechArticleIn order to achieve the separation of the program's business logic and content presentation pages to improve development speed, PHP introduced the concept of template engine , the most popular PHP template engine can be said to be smarty...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Analysis of the function and principle of nohup Analysis of the function and principle of nohup Mar 25, 2024 pm 03:24 PM

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

In-depth discussion of the principles and practices of the Struts framework In-depth discussion of the principles and practices of the Struts framework Feb 18, 2024 pm 06:10 PM

Principle analysis and practical exploration of the Struts framework. As a commonly used MVC framework in JavaWeb development, the Struts framework has good design patterns and scalability and is widely used in enterprise-level application development. This article will analyze the principles of the Struts framework and explore it with actual code examples to help readers better understand and apply the framework. 1. Analysis of the principles of the Struts framework 1. MVC architecture The Struts framework is based on MVC (Model-View-Con

How to add PPT mask How to add PPT mask Mar 20, 2024 pm 12:28 PM

Regarding PPT masking, many people must be unfamiliar with it. Most people do not understand it thoroughly when making PPT, but just make it up to make what they like. Therefore, many people do not know what PPT masking means, nor do they understand it. I know what this mask does, and I don’t even know that it can make the picture less monotonous. Friends who want to learn, come and learn, and add some PPT masks to your PPT pictures. Make it less monotonous. So, how to add a PPT mask? Please read below. 1. First we open PPT, select a blank picture, then right-click [Set Background Format] and select a solid color. 2. Click [Insert], word art, enter the word 3. Click [Insert], click [Shape]

In-depth understanding of the batch Insert implementation principle in MyBatis In-depth understanding of the batch Insert implementation principle in MyBatis Feb 21, 2024 pm 04:42 PM

MyBatis is a popular Java persistence layer framework that is widely used in various Java projects. Among them, batch insertion is a common operation that can effectively improve the performance of database operations. This article will deeply explore the implementation principle of batch Insert in MyBatis, and analyze it in detail with specific code examples. Batch Insert in MyBatis In MyBatis, batch Insert operations are usually implemented using dynamic SQL. By constructing a line S containing multiple inserted values

Detailed explanation of the principle of MyBatis paging plug-in Detailed explanation of the principle of MyBatis paging plug-in Feb 22, 2024 pm 03:42 PM

MyBatis is an excellent persistence layer framework. It supports database operations based on XML and annotations. It is simple and easy to use. It also provides a rich plug-in mechanism. Among them, the paging plug-in is one of the more frequently used plug-ins. This article will delve into the principles of the MyBatis paging plug-in and illustrate it with specific code examples. 1. Paging plug-in principle MyBatis itself does not provide native paging function, but you can use plug-ins to implement paging queries. The principle of paging plug-in is mainly to intercept MyBatis

Effects of C++ template specialization on function overloading and overriding Effects of C++ template specialization on function overloading and overriding Apr 20, 2024 am 09:09 AM

C++ template specializations affect function overloading and rewriting: Function overloading: Specialized versions can provide different implementations of a specific type, thus affecting the functions the compiler chooses to call. Function overriding: The specialized version in the derived class will override the template function in the base class, affecting the behavior of the derived class object when calling the function.

An in-depth analysis of the functions and working principles of the Linux chage command An in-depth analysis of the functions and working principles of the Linux chage command Feb 24, 2024 pm 03:48 PM

The chage command in the Linux system is a command used to modify the password expiration date of a user account. It can also be used to modify the longest and shortest usable date of the account. This command plays a very important role in managing user account security. It can effectively control the usage period of user passwords and enhance system security. How to use the chage command: The basic syntax of the chage command is: chage [option] user name. For example, to modify the password expiration date of user "testuser", you can use the following command

How to write PHP code in the browser and keep the code from being executed? How to write PHP code in the browser and keep the code from being executed? Mar 10, 2024 pm 02:27 PM

How to write PHP code in the browser and keep the code from being executed? With the popularization of the Internet, more and more people have begun to come into contact with web development, and learning PHP has also attracted more and more attention. PHP is a scripting language that runs on the server side and is often used to write dynamic web pages. However, during the exercise phase, we want to be able to write PHP code in the browser and see the results, but we don't want the code to be executed. So, how to write PHP code in the browser and keep it from being executed? This will be described in detail below. first,

See all articles