search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the usage and examples of variables in PHP template engine Smarty

This article mainly introduces the use of variables in the PHP template engine Smarty. It details the principles of Smarty templates, downloading, configuration methods and variable usage skills. Friends in need can refer to it

1. Overview:

Smarty is one of the many template engines in PHP. It is a class library written based on PHP.
Advantages of Smarty:
1. Optimize website access speed;
2. Separate web front-end design and program;

2. Installation of Smarty

1. You need to download the latest Smarty version from Smarty’s official website http://www.smarty.net/download.php. For example, the downloaded version is: Smarty-2.6.18.tar.tar;

2. Unzip the Smarty-2.6.18.tar.tar compressed package and you will find many files and folders. Except for the libs folder, deleting all others will be useless;

3. When When calling the Smarty template engine, you should first use PHP's require statement to load the file libs/Smarty.class.php.

3. Default settings of Smarty class library

require After entering the Smarty.class.php file, if you need to set the members in the Smarty class library, there are two options: There are two methods: one is to modify it directly in the Smarty.class.php file; the other is to re-specify it after initializing the class library, and the latter is generally used. The following is an explanation of the member attributes in the Smarty class library:

1, $template_dir: Set the directory where the template files in the website are stored, the default directory is templates
2, $compile_dir: Set the compilation in the website The directory where the file is stored, the default directory is templates_c
3, $config_dir: defines the directory used to store special configuration files of templates, the default is configs
4, $left_delimiter: used for the left terminator variable in the template, default It is '{'
5, $right_delimiter: used for the right terminator variable in the template, the default is '}'

4. Use of variables:

## All access in #Smarty is based on variables. The following is an example to illustrate.

Example idea: The main file introduces the template initialization configuration file (init.inc.php) and a class, and assigns values ​​to the variables in the template to display.

First, set the init.inc.php file as the initialization configuration file of the Smarty template

init.inc.php

<?php
  define(&#39;ROOT_PATH&#39;, dirname(__FILE__)); //定义网站根目录
  require ROOT_PATH.&#39;/libs/Smarty.class.php&#39;; //载入 Smarty 文件
  $_tpl = new Smarty();      //实例化一个对象
  $_tpl->template_dir = ROOT_PATH.&#39;/tpl/&#39;; //重新设置模板目录为根目录下的 tpl 目录
  $_tpl->compile_dir = ROOT_PATH.&#39;./com/&#39;; //重新设置编译目录为根目录下的 com 目录
  $_tpl->left_delimiter = &#39;<{&#39;;   //重新设置左定界符为 &#39;<{&#39;
  $_tpl->right_delimiter = &#39;}>&#39;;    //重新设置左定界符为 &#39;}>&#39;
?>

Main file index.php

<?php
  require &#39;init.inc.php&#39;; //引入模板初始化文件
  require &#39;Persion.class.php&#39;; //载入对象文件
  global $_tpl;
  $title = &#39;This is a title!&#39;;
  $content = &#39;This is body content!&#39;;
  /*
  * 一、从 PHP 中分配给模板变量;
  * 动态的数据(PHP从数据库或文件,以及算法生成的变量)
  * 任何类型的数据都可以从PHP分配过来,主要包括如下
  * 标量:string、int、double、boolean
  * 复合:array、object
  *   NULL
  * 索引数组是直接通过索引来访问的
  * 关联数组,不是使用[关联下标]而是使用 . 下标的方式
  * 对象是直接通过->来访问的
  * */
  $_tpl->assign(&#39;title&#39;,$title);
  $_tpl->assign(&#39;content&#39;,$content); //变量的赋值
  $_tpl->assign(&#39;arr1&#39;,array(&#39;abc&#39;,&#39;def&#39;,&#39;ghi&#39;));  //索引数组的赋值
  $_tpl->assign(&#39;arr2&#39;,array(array(&#39;abc&#39;,&#39;def&#39;,&#39;ghi&#39;),array(&#39;jkl&#39;,&#39;mno&#39;,&#39;pqr&#39;))); //索引二维数组的赋值
  $_tpl->assign(&#39;arr3&#39;,array(&#39;one&#39;=>&#39;111&#39;,&#39;two&#39;=>&#39;222&#39;,&#39;three&#39;=>&#39;333&#39;)); //关联数组的赋值
  $_tpl->assign(&#39;arr4&#39;,array(&#39;one&#39;=>array(&#39;one&#39;=>&#39;111&#39;,&#39;two&#39;=>&#39;222&#39;),&#39;two&#39;=>array(&#39;three&#39;=>&#39;333&#39;,&#39;four&#39;=>&#39;444&#39;))); //关联二维数组的赋值
  $_tpl->assign(&#39;arr5&#39;,array(&#39;one&#39;=>array(&#39;111&#39;,&#39;222&#39;),array(&#39;three&#39;=>&#39;333&#39;,&#39;444&#39;))); //关联和索引混合数组的赋值
  $_tpl->assign(&#39;object&#39;,new Persion(&#39;小易&#39;, 10)); //对象赋值
  //Smarty 中数值也可以进行运算(+-*/^……)
  $_tpl->assign(&#39;num1&#39;,10);
  $_tpl->assign(&#39;num2&#39;,20);
  $_tpl->display(&#39;index.tpl&#39;);
?>

Template file index.tpl of the main file index.php (stored in the /tpl/ directory)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title><{$title}></title>
  </head>  <body>
    变量的访问:<{$content}>
    <br />
    索引数组的访问:<{$arr1[0]}> <{$arr1[1]}> <{$arr1[2]}>
    <br />
    索引二维数组的访问: <{$arr2[0][0]}> <{$arr2[0][1]}> <{$arr2[0][2]}> <{$arr2[1][0]}> <{$arr2[1][1]}> <{$arr2[1][2]}>
    <br />
    关联数组的访问:<{$arr3.one}> <{$arr3.two}> <{$arr3.three}>
    <br />
    关联二维数组的访问:<{$arr4.one.one}> <{$arr4.one.two}> <{$arr4.two.three}> <{$arr4.two.four}>
    <br />
    关联和索引混合数组的访问:<{$arr5.one[0]}> <{$arr5.one[1]}> <{$arr5[0].three}> <{$arr5[0][0]}>
    <br />
    对象中成员变量的访问:<{$object->name}> <{$object->age}>
    <br />
    对象中方法的访问:<{$object->hello()}>
    <br />
    变量的运算:<{$num1+$num2}>
    <br />
    变量的混合运算:<{$num1+$num2*$num2/$num1+44}>
    <br />
  </body>
</html>

Persion.class.php

<?php
  class Persion {
   public $name; //为了访问方便,设定为public
   public $age;
   //定义一个构造方法
   public function __construct($name,$age) {
     $this->name = $name;
     $this->age = $age;
   }
   //定义一个 hello() 方法,输出名字和年龄
   public function hello() {
     return &#39;您好!我叫&#39;.$this->name.&#39;,今年&#39;.$this->age.&#39;岁了。&#39;;
   }
 }
?>

Execution result:

变量的访问:This is body content!
索引数组的访问:abc def ghi
索引二维数组的访问: abc def ghi jkl mno pqr
关联数组的访问:111 222 333
关联二维数组的访问:111 222 333 444
关联和索引混合数组的访问:111 222 333 444
对象中成员变量的访问:小易 10
对象中方法的访问:您好!我叫小易,今年10岁了。
变量的运算:30
变量的混合运算:94

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

Detailed explanation of several methods for PHP to obtain user access IP addresses

Commonly used array operations in PHP Detailed explanation of the method

php Function uses a variable number of parameter methods

The above is the detailed content of Detailed explanation of the usage and examples of variables in PHP template engine Smarty. For more information, please follow other related articles on the PHP Chinese website!

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools