Home Backend Development PHP Tutorial PHP模板引擎Smarty中变量的使用方法示例_php实例

PHP模板引擎Smarty中变量的使用方法示例_php实例

Jun 07, 2016 pm 05:07 PM
php smarty variable template engine

本文实例讲述了PHP模板引擎Smarty中变量的使用方法。分享给大家供大家参考,具体如下:

一、概述:

Smarty 是 PHP 众多模板引擎中的一个,它是根据 PHP 编写的一个类库。
Smarty 的优点:
1、优化网站访问速度;
2、网页前端设计和程序的分离;

二、Smarty 的安装

1、需要到 Smarty 的官方网站 http://www.smarty.net/download.php 下载最新的 Smarty 版本,比如下载的版本为:Smarty-2.6.18.tar.tar;

2、解压 Smarty-2.6.18.tar.tar 压缩包,会发现都很多文件和文件夹,除了 libs 文件夹外,其他的全部删除,都没有用;

3、当调用 Smarty 模板引擎时,应先使用 PHP 的 require 语句载入 libs/Smarty.class.php 这个文件。

三、Smarty 类库的默认设置

require 进 Smarty.class.php 文件后,如果需要对 Smarty 类库中的成员进行设置,有两种方法:一种是直接在 Smarty.class.php 文件中修改;一种是在初始化类库之后进行重新指定,一般使用后者。下面对 Smarty 类库中的成员属性进行说明:

1、$template_dir:设置网站中的模板文件存放的目录,默认目录是 templates
2、$compile_dir:设置网站中编译文件存放的目录,默认目录是 templates_c
3、$config_dir:定义用于存放模板特殊配置文件的目录,默认是 configs
4、$left_delimiter:用于模板中的左结束符变量,默认是 '{'
5、$right_delimiter:用于模板中的右结束符变量,默认是 '}'

四、变量的使用:

Smarty 中所有的访问都是基于变量的,下面通过一个实例来进行说明。

实例思路:主文件通过引入模板初始化配置文件(init.inc.php)和一个类,并对模板中的变量进行赋值显示。

首先,设置 init.inc.php 文件,作为 Smarty 模板的初始化配置文件
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

主文件 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

主文件 index.php 的模板文件 index.tpl(搁置在/tpl/目录下)

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

执行结果:

变量的访问: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

更多关于PHP相关内容感兴趣的读者可查看本站专题:《smarty模板入门基础教程》、《PHP模板技术总结》、《PHP基于pdo操作数据库技巧总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于smarty模板的PHP程序设计有所帮助。

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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 vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles