Table of Contents
Examples of how to use variables in PHP template engine Smarty, template smarty
Articles you may be interested in:
Home Backend Development PHP Tutorial Examples of how to use variables in PHP template engine Smarty, template smarty_PHP tutorial

Examples of how to use variables in PHP template engine Smarty, template smarty_PHP tutorial

Jul 12, 2016 am 08:54 AM
php smarty template engine

Examples of how to use variables in PHP template engine Smarty, template smarty

This article describes how to use variables in PHP template engine Smarty. Share it with everyone for your reference, the details are as follows:

1. Overview:

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

2. Smarty installation

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, it is useless to delete all others;

3. 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 methods: one is to modify it directly in the Smarty.class.php file; the other is to initialize the class The library is respecified later, generally using the latter. The following is a description of the member properties in the Smarty class library:

1. $template_dir: Set the directory where template files in the website are stored. The default directory is templates
2. $compile_dir: Set the directory where compiled files in the website are stored. The default directory is templates_c
3. $config_dir: Defines the directory used to store special configuration files for templates. The default is configs
4. $left_delimiter: used for the left terminator variable in the template, the default 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.

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

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

Copy after login

Main file index.php

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

Copy after login

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

Copy after login

Persion.class.php

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

Copy after login

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

Copy after login

Readers who are interested in more PHP-related content can check out the special topics of this site: "Basic Tutorial for Getting Started with Smarty Templates", "Summary of PHP Template Technology", "Summary of PHP Database Operation Skills Based on PDO", "PHP Operations and Operators" Usage summary", "PHP network programming skills summary", "PHP basic syntax introductory tutorial", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php mysql database operation introductory tutorial" and "Summary of Common Database Operation Skills in PHP"

I hope this article will be helpful to everyone’s PHP program design based on smarty templates.

Articles you may be interested in:

  • Detailed explanation of the built-in functions of PHP template engine Smarty
  • Detailed explanation of the usage of the built-in variable mediator of PHP template engine Smarty
  • PHP Template engine Smarty custom variable mediator usage
  • Usage analysis of reserved variables in PHP template engine Smarty
  • PHP template engine Smarty built-in function foreach, foreachelse usage analysis
  • PHP Example of how to use the configuration file of the template engine Smarty in template variables
  • How the smarty template engine obtains data from php
  • ThinkPHP How to use the smarty template engine
  • In Detailed explanation of the random number generation method and math function of PHP template engine smarty
  • Summary of cache usage of PHP template engine Smarty
  • 6 tips for PHP smarty template engine
  • [PHP ] An in-depth introduction to the template engine Smarty
  • Detailed explanation of the usage of the built-in functions section and sectionelse of the PHP template engine Smarty

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1119979.htmlTechArticleExamples of how to use variables in PHP template engine Smarty, template smarty This article describes the use of variables in PHP template engine Smarty How to use. Share it with everyone for your reference, the details are as follows:...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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

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

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

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