模板显示变量

原创 2018-12-13 16:08:36 316
摘要:<?php session_start(); //加载Smart配置 require __DIR__ . '/config/config.php'; //1.显示单值变量 $name = 'Eddie Fu'; $smarty->assign('name',$name);
<?php
session_start();
//加载Smart配置

require __DIR__ . '/config/config.php';

//1.显示单值变量
$name = 'Eddie Fu';
$smarty->assign('name',$name);

//2.数组:索引数组
$courses = ['html5', 'css3', 'jQuery', 'php', 'mysql'];
$smarty->assign('courses', $courses);

//3.数组:关联数组
$book = ['name'=>'PHP开发','price'=>69, 'publish'=>'2018-04-22'];
$smarty->assign('book', $book);

//4.多维数组
$books = [
    ['name'=>'PHP开发','price'=>69, 'publish'=>'2018-04-22'],
    ['name'=>'MySQL性能分析', 'price'=>39, 'publish'=>'2017-10-10'],
    ['name'=>'JavaScript高级教程', 'price'=>99, 'publish'=>'2016-03-18'],
];
$smarty->assign('books', $books);

//5. 对象
class Test
{
    public $site = 'PHP中文网';
    public function welcome()
    {
        return '欢迎来到'.$this->site;
    }
}
$test = new Test;
$smarty->assign('test',$test);

//自定义函数
function add($a, $b)
{
    return $a+$b;
}

//常量
const SITE_NAME = 'php中文网';
//常量作用域是全局,不必模板赋值可以直接输出

//系统变量
$_POST['user_name'] = '用户名';
$_GET['page'] ;
$_SESSION['pass'] = sha1(666);
//不用调用 assign()进行模板赋值,可以直接在模板中输出

$smarty->display('demo66.html');
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>demo66</title>
</head>
<body>
{*注释: 显示变量*}
<h3>Name: {$name}</h3>
<hr>

{* 显示索引数组 *}
<p>前端课程: {$courses.0},{$courses.1},{$courses.2}</p>

{* 显示关联数组 *}
<p>书名:《{$book.name}》,价格:{$book['price']}元,出版时间:{$book.publish}</p>

{* 显示多维数组 *}
<p>书名:《{$books.1.name}》,价格:{$books[1]['price']}元,出版时间:{$books.1.publish}</p>
<hr>

{* 显示对象成员 *}
<p>我是:{$test->site}, {$test->welcome()}</p>
<hr>


{* 模板中直接使用表达式 *}
<p>涨价啦~~ {$book['price'] + 100}</p>

{* 模板中使用系统函数 *}
<p>出版时间: {str_replace('-', '/',$book.publish)}</p>

{* 模板中使用用户自定义函数 *}
<p>新的价格是: {add($book.price, 200)}</p>

{* 直接解析双引号中的变量 *}
<p>普通变量,我的名字: {" $name "}</p>
{* 数组或对象变量要加反引号 *}
<p>复合变量:数组/对象:书名是: {" `$book.name` "}</p>

{* 输出常量 *}
<p>站点名称: {$smarty.const.SITE_NAME}</p>

{* 输出系统变量 *}
<p>POST提交的用户名是: {$smarty.post.user_name}</p>
<p>GET传入的当前页数是: {$smarty.get.page}</p>
<p>SESSION会话中的密码是: {$smarty.session.pass}</p>

{* 读取配置文件信息 *}
{* 读取全局配置 *}
{* 加载配置文件 *}
{config_load file="user.conf"}
<p>应用编号是: {$smarty.config.app_number}</p>

{* 读取配置文件中的局部配置[section]区内容 *}
{* 加载配置文件中的局部区块配置信息 *}
{config_load file="user.conf" section="database"}
<p>数据库编号: {$smarty.config.db_number}</p>

</body>
</html>

user.conf

#应用配置文件
app_number = 111

[database]
db_number = 111

总结:

普通变量

脚本 $smarty->assign('nm',$name);

模板 使用{$nm}

模板中的数组{$books.1.name}

使用常量{$smarty.const.SITE_NAME}

系统变量{$smarty.post.un}

模板读取全局配置

{config_load file="user.conf"}

<p>应用编号是: {$smarty.config.app_number}</p>

模板读取局部配置

{config_load file="user.conf" section="database"}

<p>数据库编号: {$smarty.config.db_number}</p>


批改老师:韦小宝批改时间:2018-12-13 16:35:13
老师总结:写的很不错哦!思路清晰!代码完整!注释写的也很清楚!

发布手记

热门词条