


Examples of how to use variables in PHP template engine Smarty, template smarty_PHP tutorial
Jul 12, 2016 am 08:54 AMExamples 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
<?php define('ROOT_PATH', dirname(__FILE__)); //定義網(wǎng)站根目錄 require ROOT_PATH.'/libs/Smarty.class.php'; //載入 Smarty 文件 $_tpl = new Smarty(); //實(shí)例化一個(gè)對(duì)象 $_tpl->template_dir = ROOT_PATH.'/tpl/'; //重新設(shè)置模板目錄為根目錄下的 tpl 目錄 $_tpl->compile_dir = ROOT_PATH.'./com/'; //重新設(shè)置編譯目錄為根目錄下的 com 目錄 $_tpl->left_delimiter = '<{'; //重新設(shè)置左定界符為 '<{' $_tpl->right_delimiter = '}>'; //重新設(shè)置左定界符為 '}>' ?>
Main file index.php
<?php require 'init.inc.php'; //引入模板初始化文件 require 'Persion.class.php'; //載入對(duì)象文件 global $_tpl; $title = 'This is a title!'; $content = 'This is body content!'; /* * 一、從 PHP 中分配給模板變量; * 動(dòng)態(tài)的數(shù)據(jù)(PHP從數(shù)據(jù)庫(kù)或文件,以及算法生成的變量) * 任何類型的數(shù)據(jù)都可以從PHP分配過來,主要包括如下 * 標(biāo)量:string、int、double、boolean * 復(fù)合:array、object * NULL * 索引數(shù)組是直接通過索引來訪問的 * 關(guān)聯(lián)數(shù)組,不是使用[關(guān)聯(lián)下標(biāo)]而是使用 . 下標(biāo)的方式 * 對(duì)象是直接通過->來訪問的 * */ $_tpl->assign('title',$title); $_tpl->assign('content',$content); //變量的賦值 $_tpl->assign('arr1',array('abc','def','ghi')); //索引數(shù)組的賦值 $_tpl->assign('arr2',array(array('abc','def','ghi'),array('jkl','mno','pqr'))); //索引二維數(shù)組的賦值 $_tpl->assign('arr3',array('one'=>'111','two'=>'222','three'=>'333')); //關(guān)聯(lián)數(shù)組的賦值 $_tpl->assign('arr4',array('one'=>array('one'=>'111','two'=>'222'),'two'=>array('three'=>'333','four'=>'444'))); //關(guān)聯(lián)二維數(shù)組的賦值 $_tpl->assign('arr5',array('one'=>array('111','222'),array('three'=>'333','444'))); //關(guān)聯(lián)和索引混合數(shù)組的賦值 $_tpl->assign('object',new Persion('小易', 10)); //對(duì)象賦值 //Smarty 中數(shù)值也可以進(jìn)行運(yùn)算(+-*/^……) $_tpl->assign('num1',10); $_tpl->assign('num2',20); $_tpl->display('index.tpl'); ?>
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 /> 索引數(shù)組的訪問:<{$arr1[0]}> <{$arr1[1]}> <{$arr1[2]}> <br /> 索引二維數(shù)組的訪問: <{$arr2[0][0]}> <{$arr2[0][1]}> <{$arr2[0][2]}> <{$arr2[1][0]}> <{$arr2[1][1]}> <{$arr2[1][2]}> <br /> 關(guān)聯(lián)數(shù)組的訪問:<{$arr3.one}> <{$arr3.two}> <{$arr3.three}> <br /> 關(guān)聯(lián)二維數(shù)組的訪問:<{$arr4.one.one}> <{$arr4.one.two}> <{$arr4.two.three}> <{$arr4.two.four}> <br /> 關(guān)聯(lián)和索引混合數(shù)組的訪問:<{$arr5.one[0]}> <{$arr5.one[1]}> <{$arr5[0].three}> <{$arr5[0][0]}> <br /> 對(duì)象中成員變量的訪問:<{$object->name}> <{$object->age}> <br /> 對(duì)象中方法的訪問:<{$object->hello()}> <br /> 變量的運(yùn)算:<{$num1+$num2}> <br /> 變量的混合運(yùn)算:<{$num1+$num2*$num2/$num1+44}> <br /> </body> </html>
Persion.class.php
<?php class Persion { public $name; //為了訪問方便,設(shè)定為public public $age; //定義一個(gè)構(gòu)造方法 public function __construct($name,$age) { $this->name = $name; $this->age = $age; } //定義一個(gè) hello() 方法,輸出名字和年齡 public function hello() { return '您好!我叫'.$this->name.',今年'.$this->age.'歲了。'; } } ?>
Execution result:
變量的訪問:This is body content! 索引數(shù)組的訪問:abc def ghi 索引二維數(shù)組的訪問: abc def ghi jkl mno pqr 關(guān)聯(lián)數(shù)組的訪問:111 222 333 關(guān)聯(lián)二維數(shù)組的訪問:111 222 333 444 關(guān)聯(lián)和索引混合數(shù)組的訪問:111 222 333 444 對(duì)象中成員變量的訪問:小易 10 對(duì)象中方法的訪問:您好!我叫小易,今年10歲了。 變量的運(yùn)算:30 變量的混合運(yùn)算:94
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

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

The urlencode() function is used to encode strings into URL-safe formats, where non-alphanumeric characters (except -, _, and .) are replaced with a percent sign followed by a two-digit hexadecimal number. For example, spaces are converted to signs, exclamation marks are converted to!, and Chinese characters are converted to their UTF-8 encoding form. When using, only the parameter values ??should be encoded, not the entire URL, to avoid damaging the URL structure. For other parts of the URL, such as path segments, the rawurlencode() function should be used, which converts the space to . When processing array parameters, you can use http_build_query() to automatically encode, or manually call urlencode() on each value to ensure safe transfer of data. just

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.

There are two main ways to get the last N characters of a string in PHP: 1. Use the substr() function to intercept through the negative starting position, which is suitable for single-byte characters; 2. Use the mb_substr() function to support multilingual and UTF-8 encoding to avoid truncating non-English characters; 3. Optionally determine whether the string length is sufficient to handle boundary situations; 4. It is not recommended to use strrev() substr() combination method because it is not safe and inefficient for multi-byte characters.

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

Key methods to prevent SQL injection in PHP include: 1. Use preprocessing statements (such as PDO or MySQLi) to separate SQL code and data; 2. Turn off simulated preprocessing mode to ensure true preprocessing; 3. Filter and verify user input, such as using is_numeric() and filter_var(); 4. Avoid directly splicing SQL strings and use parameter binding instead; 5. Turn off error display in the production environment and record error logs. These measures comprehensively prevent the risk of SQL injection from mechanisms and details.
