search
HomeBackend DevelopmentPHP TutorialSpecific guide to using PHP template Smarty_PHP tutorial

Specific guide to using PHP template Smarty_PHP tutorial

Jul 15, 2016 pm 01:30 PM
phpsmartydeliveruser's guidancespecificbackusmethodtemplateofprogramsolvedesignpage

Usually our solution is to have the artist design the page and hand it over to the programmer for development, and then hand it over to the artist to improve the page, repeating it several times. If the programmer encounters a problem If you are not familiar with HTML, it will be a painful task for both parties and the efficiency will be lower. At this time, it is very important to have template support.

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 the most commonly used PHP template engine today. I will share it with you today How to install and use PHP template Smarty in PHP development can also be regarded as an introduction to Smarty.

Preparation

1. Select the directory where Smarty is installed

If you have server permissions, consider security. 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 PHP template 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, I chose Smarty-2.6.25

PHP template Smarty installation steps

1. Unzip the downloaded 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.

Using PHP template Smarty

1. Create related directories

Due to the process of using Smarty, Smarty will generate For compiled template files, other configuration files, and cache files, we need to create relevant 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 caching feature is enabled, all templates cached by PHP Template 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 related configuration files

We need to create a configuration file to override the default member attributes of the PHP template Smarty class, and name it main.php, save it In the smarty directory, which script needs to use Smarty in the future, we only need to include main.php.

<ol class="dp-xml">
<li class="alt"><span><span class="tag"><span> ?  </span></span></span></li>
<li><span>include("./smarty/libs/Smarty.class.php");  </span></li>
<li class="alt"><span>define('SMARTY_ROOT', './smarty/tpls');  </span></li>
<li>
<span>$</span><span class="attribute">tpl</span><span> = </span><span class="attribute-value">new</span><span> Smarty();  </span>
</li>
<li class="alt">
<span>$tpl-</span><span class="tag">></span><span class="attribute">template_dir</span><span> = </span><span class="attribute-value">SMARTY_ROOT</span><span>."/templates/";  </span>
</li>
<li>
<span>$tpl-</span><span class="tag">></span><span class="attribute">compile_dir</span><span> = </span><span class="attribute-value">SMARTY_ROOT</span><span>."/templates_c/";  </span>
</li>
<li class="alt">
<span>$tpl-</span><span class="tag">></span><span class="attribute">config_dir</span><span> = </span><span class="attribute-value">SMARTY_ROOT</span><span>."/configs/";  </span>
</li>
<li>
<span>$tpl-</span><span class="tag">></span><span class="attribute">cache_dir</span><span> = </span><span class="attribute-value">SMARTY_ROOT</span><span>."/cache/";  </span>
</li>
<li class="alt">
<span>$tpl-</span><span class="tag">></span><span class="attribute">caching</span><span>=</span><span class="attribute-value">1</span><span>;  </span>
</li>
<li>
<span>$tpl-</span><span class="tag">></span><span class="attribute">cache_lifetime</span><span>=</span><span class="attribute-value">60</span><span>*60*24;  </span>
</li>
<li class="alt">
<span>$tpl-</span><span class="tag">></span><span class="attribute">left_delimiter</span><span> = </span><span class="attribute-value">'<span>;  </span></span>
</li>
<li>
<span>$tpl-</span><span class="tag">></span><span class="attribute">right_delimiter</span><span> = </span><span class="attribute-value">'}>'</span><span>;  </span>
</li>
<li class="alt">
<span class="tag">?></span><span> </span>
</li>
</ol>

Note:

Lines 1-8: Mainly define a smarty object, and set the template file, compiled file, cache file, and configuration file at the same time Storage directory, overwriting the default value in Smarty.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 PHP template 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、建立一个模板文件

一般情况下在美工页面设计完毕后,双方的交集点是模版文件,双方约定后,程序员不需要花太大的精力在前台,这就是使用Smarty模板引擎进行开发的好处。

我们首先建立一个简单的模版文件,名为leapsoul.tpl,你可在html文件中加入smarty变量后将文件另存为tpl类型的文件。

<ol class="dp-xml">
<li class="alt"><span><span class="tag"><span> </span><span class="tag-name">html</span><span class="tag">></span><span> </span></span></span></li>
<li><span class="tag"><span> </span><span class="tag-name">head</span><span class="tag">></span><span> </span></span></li>
<li class="alt"><span class="tag"><span> </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> <br></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> </span><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> /title</span><span class="tag">></span><span>   </span></span></li>
<li class="alt"><span class="tag"><span> /head</span><span class="tag">></span><span>   </span></span></li>
<li>
<span> </span><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> /body</span><span class="tag">></span><span>   </span></span></li>
<li class="alt"><span class="tag"><span> /html</span><span class="tag">></span><span> </span></span></li>
</ol>

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

4、建立应用程序文件

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

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

注释:

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

其他说明

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

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


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446267.htmlTechArticle通常我们的解决方法是由美工设计页面后交付程序设计者进行开发,再交付美工对页面进行改善,来回重复好几回,如果遇到程序设计者对...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor