Home Backend Development PHP Tutorial Smarty Tutorial for PHP Template_PHP Tutorial

Smarty Tutorial for PHP Template_PHP Tutorial

Jul 20, 2016 am 10:57 AM
php smarty Open source engine us supply Tutorial template of Know Community language

We know that the PHP language, as a member of the open source community, provides various template engines, such as FastTemplate, Smarty, SimpleTemplate, etc., and Smarty is now used There are many PHP template engines. Today I will share with you how to install and use Smarty in PHP development. It can also be regarded as an introduction to Smarty.

1. Preparation

1. Select the directory where Smarty is installed

If you have server permissions, consider security You can choose to install Smarty outside the WEB program's documentation directory, and then include the address of the Smarty installation directory in the include_path option in the PHP.INI file.

If you have virtual host permissions or several projects, you can install Smarty in their respective project directories. You can also use the Smarty template engine in the require Smarty class file. Of course, for security reasons, you can prohibit access to related directories through apache.

In addition, the two Smarty installation methods are different in terms of portability. The first method needs to ensure that each server has the same Smarty configuration, while the second method has no impact on the configuration of each server. You can choose the installation method of Smarty according to your own needs.

2. Download Smarty, please click here to download Smarty. I chose Smarty-2.6.25

Smarty installation steps

1. Unzip Download the Smarty-2.6.25 compressed package

2. Copy the libs folder to the WEB program directory. My directory is testsmarty

You can refer to here for the installation method under Linux.

After installing the Smarty template, we started to use Smarty simply.

3. Using Smarty

1. Create relevant directories

Due to the process of using Smarty, Smarty will generate compiled template files and other Configuration files and cache files, we need to create related directories. I created another tpls directory in the testsmarty directory, and created templates, templates_c, configs, and cache directories in the tpls directory. Why do we need to create these directories? Open the Smarty.class.php file, and we can see that the Smarty class defines some member attributes.

$template_dir: Set the directory address where all template files need to be placed. By default, the directory is: "./templates", that is, the template directory is found in the same directory as the PHP execution program.

$compile_dir: Set the storage directory address of all template files compiled by Smarty. The default directory is: "./templates_c", that is, the compilation directory is found in the same directory as the PHP execution program. If you create this directory on a Linux server, you also need to modify the permissions of this directory so that it has write permissions.

$config_dir: Set the directory used to store special configuration files for templates. The default directory is: "./configs", that is, the configuration directory is found in the same directory as the PHP execution program.

$cache_dir: When the cache feature is enabled, all templates cached by Smarty are placed in the directory specified by this attribute. The default directory is: "./cache", that is, the cache directory is found in the same directory as the PHP execution program. You can also use your own custom cache handler to control cached files, which will ignore this setting. Similarly, if you create this directory on a Linux server, you also need to modify the permissions of this directory so that it has write permissions.

For system security and portability considerations, it is recommended not to create these directories in the same directory as the PHP executable program. You can create them outside the PHP executable program directory. If they have been created in the same directory as the PHP executable program , you can use Apache to restrict directory access.

2. Create relevant configuration files

We need to create a configuration file to override the default member attributes of the Smarty class, name it main.php, and save it in the smarty directory. Which script will be used in the future? To use Smarty, we only need to include main.php.

<ol class="dp-c">
<li class="alt"><span><span><?  </span></span></li><li><span class="keyword">include</span><span>(</span><span class="string">"./smarty/libs/Smarty.class.php"</span><span>);  </span></li><li class="alt"><span>define(</span><span class="string">'SMARTY_ROOT'</span><span>, </span><span class="string">'./smarty/tpls'</span><span>);  </span></li><li><span class="vars">$tpl</span><span> = </span><span class="keyword">new</span><span> Smarty();  </span></li><li class="alt"><span class="vars">$tpl</span><span>->template_dir = SMARTY_ROOT.</span><span class="string">"/templates/"</span><span>;  </span></span></li>
<li>
<span class="vars">$tpl</span><span>->compile_dir = SMARTY_ROOT.</span><span class="string">"/templates_c/"</span><span>;  </span>
</li>
<li class="alt">
<span class="vars">$tpl</span><span>->config_dir = SMARTY_ROOT.</span><span class="string">"/configs/"</span><span>;  </span>
</li>
<li>
<span class="vars">$tpl</span><span>->cache_dir = SMARTY_ROOT.</span><span class="string">"/cache/"</span><span>;  </span>
</li>
<li class="alt">
<span class="vars">$tpl</span><span>->caching=1;  </span>
</li>
<li>
<span class="vars">$tpl</span><span>->cache_lifetime=60*60*24;  </span>
</li>
<li class="alt">
<span class="vars">$tpl</span><span>->left_delimiter = </span><span class="string">'<{'</span><span>;  </span></li><li><span class="vars">$tpl</span><span>->right_delimiter = </span><span class="string">'}>'</span><span>;  </span>
</li>
<li class="alt"><span>?> </span></li>
</ol>
Copy after login

Notes:

Lines 1-8: Mainly define a smarty object, and also set the storage directory for template files, compiled files, cache files, and configuration files, covering Smarty. Default value in class.php.

Lines 9-10: Set to enable caching and set the cache validity time to 1 day.

Knowledge point: $caching is used to set whether to enable the cache function. Default value is set to 0 or invalid. You can also have multiple caches for the same template, and enable caching when the value is 1 or 2. 1 tells Smarty to use the current $cache_lifetime variable to determine whether the cache has expired. 2 Tell Smarty to use the cache_lifetime value when generating the cache. It is recommended to turn off the cache during project development and set the value to 0

Lines 11-12: Set the left and right terminators of the smarty language. We know that curly brackets are the default delimiters of smarty, but when used with javascript , css, etc. may cause conflicts, so here we set it to <{and}>.

3. Create a template file

Generally, after the art page is designed, the intersection point between the two parties is the template file. After the two parties agree, the programmer does not need to spend too much energy on it. Front desk, this is the benefit of using Smarty template engine for development.

We first create a simple template file named leapsoul.tpl. You can add smarty variables to the html file and save the file as a tpl type file.

<ol class="dp-xml">
<li class="alt"><span><span class="tag"><</span><span class="tag-name">html</span><span class="tag">></span><span> </span></span></li>
<li>
<span class="tag"><</span><span class="tag-name">head</span><span class="tag">></span><span> </span>
</li>
<li class="alt">
<span class="tag"><</span><span class="tag-name">meta</span><span> </span><span class="attribute">http-equiv</span><span>=</span><span class="attribute-value">"Content-type"</span><span> </span><span class="attribute">content</span><span>=</span><span class="attribute-value">"text/html; charset=gb2312"</span><span class="tag">></span><span> </span>
</li>
<li>
<span class="tag"><</span><span class="tag-name">title</span><span class="tag">></span><span>   </span>
</li>
<li class="alt">
<span class="tag"><</span><span>{ $title }</span><span class="tag">></span><span> </span>
</li>
<li>
<span class="tag"></</span><span class="tag-name">title</span><span class="tag">></span><span>   </span>
</li>
<li class="alt">
<span class="tag"></</span><span class="tag-name">head</span><span class="tag">></span><span>   </span>
</li>
<li>
<span class="tag"><</span><span class="tag-name">body</span><span class="tag">></span><span>   </span>
</li>
<li class="alt">
<span class="tag"><</span><span>{ $content }</span><span class="tag">></span><span>   </span>
</li>
<li>
<span class="tag"></</span><span class="tag-name">body</span><span class="tag">></span><span>   </span>
</li>
<li class="alt">
<span class="tag"></</span><span class="tag-name">html</span><span class="tag">></span><span> </span>
</li>
</ol>
Copy after login

注释:在这个tpl文件中设定了title和content两个smarty变量,文件保存为leapsoul.tpl,同时将其保存在testsmartytplstemplates模板文件目录下。

4、建立应用程序文件

模版文件类似于一个表现层,在建立完模板文件后,我们需要一个应用程序去驱动表现层,应用程序文件定义为smarty.php。

<ol class="dp-c">
<li class="alt"><span><span><?  </span></span></li><li><span class="keyword">include</span><span>(</span><span class="string">"smarty/main.php"</span><span>);  </span></li><li class="alt"><span class="vars">$tpl</span><span>->assign(</span><span class="string">"title"</span><span>, </span><span class="string">"leapsoul.cn为你展示smarty模板技术"</span><span>);  </span></span></li>
<li>
<span class="vars">$tpl</span><span>->assign(</span><span class="string">"content"</span><span>, </span><span class="string">"leapsoul.cn通过详细的安装使用步骤为你展示smarty模板技术"</span><span>);  </span>
</li>
<li class="alt">
<span class="vars">$tpl</span><span>->display(</span><span class="string">"leapsoul.tpl"</span><span>);  </span>
</li>
<li><span>?> </span></li>
</ol>
Copy after login

注释:

在这段代码中我们主要用到smarty中的两个函数assign和display,assign你可以理解为为变量赋值,display主要是用来将网页输出。更多smarty函数今后会详细介绍。

其他说明

由于我们开启了缓存功能,有兴趣的朋友可以打开cache和templates_c,cache目录存放了这个模板的缓存文件,文件开头部分有缓存信息,如文件的生成时间和过期时间等,其他的和一般的HTML文件没有多大的区别,而templates_c存放了模板经过编译后的PHP执行文件。

至此一个简单入门的Smarty模板应用实例就算介绍完成了。

原文地址:http://www.leapsoul.cn/?p=405


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445775.htmlTechArticle我们知道 PHP 语言作为开源社区的一员,提供了各种模板引擎,如FastTemplate, Smarty ,SimpleTemplate等,而Smarty是现在使用得比较多的PHP模板引...
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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles