search
HomeBackend DevelopmentPHP TutorialSmarty Tutorial for PHP Template_PHP Tutorial

Smarty Tutorial for PHP Template_PHP Tutorial

Jul 20, 2016 am 10:57 AM
phpsmartyOpen sourceengineussupplyTutorialtemplateofKnowCommunitylanguage

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>
</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>

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 .

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 class="tag-name">html</span><span class="tag">></span><span> </span></span></span></li>
<li><span class="tag"><span class="tag-name">head</span><span class="tag">></span><span> </span></span></li>
<li class="alt"><span class="tag"><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></span></li>
<li><span class="tag"><span class="tag-name">title</span><span class="tag">></span><span>   </span></span></li>
<li class="alt"><span class="tag"><span>{ $title }</span><span class="tag">></span><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 class="tag-name">body</span><span class="tag">></span><span>   </span></span></li>
<li class="alt"><span class="tag"><span>{ $content }</span><span class="tag">></span><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>

注释:在这个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>
</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>

注释:

在这段代码中我们主要用到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
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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.