smarty template is used in PHP to separate the logic of PHP code that is originally mixed with HTML code; smarty is a template engine written in PHP. smarty separates the logic code and external content, providing It provides an easy-to-manage and use method to achieve the effect of logical separation of html and PHP code. The import syntax is "require_once('...Smarty.php')".
The operating environment of this article: Windows 10 system, PHP version 8.1, Dell G3 computer
Smarty is a template engine written in PHP and is one of the most famous PHP template engines in the industry. It separates logical code and external content, providing an easy-to-manage and use method to separate PHP code logic that is originally mixed with HTML code.
To put it simply, the purpose is to separate PHP programmers from front-end personnel, so that programmers change the logical content of the program without affecting the page design of the front-end personnel, and front-end personnel re-modify the page without affecting the program. Program logic, which is particularly important in multi-person collaboration projects.
Advantages
1. Speed: Programs written using Smarty can achieve maximum speed improvements, which is compared to other template engine technologies.
2. Compiled type: A program written in Smarty needs to be compiled into a non-template technology PHP file at runtime. This file uses a mixture of PHP and HTML, and the WEB request will be made directly the next time the template is accessed. Convert to this file without recompiling the template (when the source program has not been changed)
3. Caching technology: a caching technology selected by Smarty, which can store the content that the user finally sees. The HTML file is cached into a static HTML page. When Smarty's cache attribute is set to true, the user's WEB request is directly converted to this static HTML file within the cachetime set by Smarty. This is equivalent to calling a Static HTML files.
4. Plug-in technology: Smarty can customize plug-ins. Plug-ins are actually some custom functions.
5. If/elseif/else/endif can be used in templates. Using judgment statements in template files can very conveniently reformat the template.
smarty installation
composer downloads smarty
composer require smarty/smarty
Import smarty and create smarty objects
//引入Smarty.class.php require_once('../vendor/smarty/smarty/libs/Smarty.class.php'); $smarty = new Smarty();
smarty basic directory configuration
$smarty->setTemplateDir('./templates/'); $smarty->setCompileDir('./templates_c/'); $smarty->setConfigDir('./configs/'); $smarty->setCacheDir('./cache/');
smarty assign variables
$name = 'smarty'; $smarty->assign('name',$name);
tpl template uses variables
{$name} 、
smarty calls template
$smarty->display('index.tpl');
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to use smarty in php. For more information, please follow other related articles on the PHP Chinese website!