学习目标模板引擎的工作原理Smarty入门Smarty...
请注意,本文编写于 1727 天前,最后修改于 996 天前,其中某些信息可能已经过时。
实现HTML代码和PHP代码分离的目的是:实现前端设计人员和PHP程序员的分离。
多数Web开发人员要么是精通网页设计,能够设计出漂亮的网页外观,但是编写的PHP代码很糟糕;要么仅熟悉PHP编程,能够写出健壮的PHP代码,但是设计的网页外观很难看。具备两种才能的开发人员很少见。
将PHP和HTML混合页面,分成两个独立的页面:
一个是HTML静态页面(视图文件、模板文件),扩展名是.html,包含HTML、CSS、JS
一个是纯PHP程序页面(控制器文件),扩展名是.php,主要PHP代码。
运行时,将HTML文件代码,包含到PHP文件中。
实现PHP与静态文件的简单分离:
<?php
/**
* 本页PHP程序...
*/
// 引入HTML静态文件
include './demo.html';
为啥要用include
而不用require
?因为静态文件中没有类、函数的定义,使用include
可以降低服务器压力(我自己猜的。。。)。
**<?php echo $name ?>**
str_replace()
,将 {
替换成 <?php echo
,将}
替换成?>
。简单实现:
<?php
// 编写本页程序
$name = '猪八戒';
$age = 22;
// 读取引入页面
$str = file_get_contents('./demo.html');
// 对读取的内容进行替换
$str = str_replace('{', '<?php echo ', $str);
$str = str_replace('}', ' ?>', $str);
// 将替换后的字符串写入原文件
file_put_contents('./demo.html', $str);
// 引入替换后的文件
include './demo.html';
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1> {$name}今年{$age}岁了!!!</h1>
</body>
</html>
示例代码
Smarty是一个使用PHP写出来的模板引擎,是目前业界最著名的PHP模板引擎之一。它分离了逻辑代码和外在的内容,提供了一种易于管理和使用的方法,用来将原本与HTML代码混杂在一起PHP代码逻辑分离。简单的讲,目的就是要使PHP程序员同前端人员分离,使程序员改变程序的逻辑内容不会影响到前端人员的页面设计,前端人员重新修改页面不会影响到程序的程序逻辑,这在多人合作的项目中显的尤为重要。
PHP文件代码:
<?php
// 引入Smarty类
include_once('./Smart/libs/Smarty.class.php');
// 实例化Smarty类对象
$smarty = new Smarty();
// 使用Smarty对变量赋值
$smarty->assign('name', '猪八戒');
$smarty->assign('age', 22);
// 引入前端展示文件
$smarty->display('./demo.html');
HTML前端展示页面代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1> {$name}今年{$age}岁了!!!</h1>
</body>
</html>
在Smarty中,默认使用 "{" 和 "}"作为变量的定界符。但这样,会与CSS、JS中的大括号冲突。
// Smarty类边界符重新定义
$smarty->left_delimiter = '<{';
$smarty->right_delimiter = '}>';
// 设置Smarty的视图文件根目录
$smarty->setTemplateDir('./view');
目录类别 | 默认目录 | 修改方法 | 查看方法 |
---|---|---|---|
Smarty默认模板目录 | ./templates | $smarty->setTemplateDir() | $smarty->getTemplateDir() |
Smarty默认配置目录 | ./configs | $smarty->setConfigDir() | $smarty->getConfigDir() |
Smarty默认编译目录 | ./templates_c | $smarty->setCompileDir() | $smarty->getCompileDir() |
Smarty默认缓存目录 | ./cache | $smarty->setCacheDir() | $smarty->getCacheDir() |
Smarty默认插件目录 | ./libs/plugins | $smarty->setPluginsDir() | $smarty->getPluginsDir() |
查看Smarty常用目录配置:Smarty类文件中的__construct()构造方法
$smarty->assign()
向Smarty模板传递普通变量;$smarty->display()
显示指定的视图文件;PHP文件:
<?php
// 引入Smarty类
include_once('./Smart/libs/Smarty.class.php');
// 实例化Smarty类对象
$smarty = new Smarty();
// 设置Smarty的视图文件根目录
$smarty->setTemplateDir('./view');
// 使用Smarty对变量赋值
$smarty->assign('name', '猪八戒');
$smarty->assign('age', 22);
$smarty->assign('is_married', true);
$smarty->assign('money', 1234.44545);
// 创建一个学生类
class Student
{
const TITLE = '学生';
}
$stu = new Student;
$smarty->assign('student', $stu);
// 引入前端展示文件
$smarty->display('./demo.html');
HTML文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
background-color: #fff;
}
</style>
</head>
<body>
<h1>
{$name}今年 {$age}岁了!!!职业是{$student::TITLE},工资{$money},婚姻状况为{$is_married}.
</h1>
</body>
</html>
注意:这些变量名为系统定义!
语法:{$smarty.const.预定义常量}
语法:{$smarty.now}
网站上有一些比较简单的变量信息,美工人员可以自行定义并调用。这样可以脱离程序员的依赖,工作比较有主动权。
载入分组配置文件变量:**{config_load file = “配置文件路径” section = “分组名”}
PHP页面:
<?php
// 引入Smarty类
include_once('./Smart/libs/Smarty.class.php');
// 实例化Smarty类对象
$smarty = new Smarty();
// 设置Smarty的视图文件根目录
$smarty->setTemplateDir('./view');
// 创建一个枚举数组
$db_info = array(
'db_host' => 'localhost',
'username' => 'root',
'password' => 'root',
'db_name' => 'demo'
);
// 使用Smarty对变量赋值
$smarty->assign('db_info', $db_info);
// 引入前端展示文件
$smarty->display('./demo.html');
HTML前端展示页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
background-color: #fff;
}
</style>
</head>
<body>
<h1>循环输出枚举数组</h1>
{foreach $db_info as $key=>$value} {$key} {$value};<br> {/foreach}
<h1>循环输出枚举数组(第二种方式)</h1>
{foreach from=$db_info key='key' item='value'} {$key} {$value};<br> {/foreach}
</body>
</html>
PHP页面:
<?php
// 引入Smarty类
include_once('./Smart/libs/Smarty.class.php');
// 实例化Smarty类对象
$smarty = new Smarty();
// 设置Smarty的视图文件根目录
$smarty->setTemplateDir('./view');
//创建一个二维数组
$stu_info = array(
array(10010, '张三', '男', 24, 6000, 300),
array(10020, '李四', '女', 28, 9000, 200),
array(10030, '周五', '男', 29, 12000, 340),
array(10040, '陆六', '女', 26, 9800, 230)
);
// 使用Smarty对变量赋值
$smarty->assign('stu_info', $stu_info);
// 引入前端展示文件
$smarty->display('./demo.html');
HTML前端展示页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
background-color: #fff;
}
</style>
</head>
<body>
<table border="1">
{foreach $stu_info as $arr}
<tr>
{foreach $arr as $value}
<td>
{$value}
</td>
{/foreach}
</tr>
{/foreach}
</table>
</body>
</html>
PHP页面:
<?php
// 引入Smarty类
include_once('./Smart/libs/Smarty.class.php');
// 实例化Smarty类对象
$smarty = new Smarty();
// 设置Smarty的视图文件根目录
$smarty->setTemplateDir('./view');
// 创建一个枚举数组
$db_info = array(
'db_host' => 'localhost',
'username' => 'root',
'password' => 'root',
'db_name' => 'demo'
);
// 使用Smarty对变量赋值
$smarty->assign('db_info', $db_info);
// 引入前端展示文件
$smarty->display('./demo.html');
HTML前端展示页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Smarty模板引擎</title>
<style type="text/css">
body {
background-color: #99ff00;
}
</style>
</head>
<body>
<table border="1">
{foreach $db_info as $value} {if $value@first}
<tr>
<th>值</th>
<th>索引</th>
<th>从0开始计数</th>
<th>从1开始计数</th>
<th>是否为第1次循环</th>
<th>是否为最后1次循环</th>
<th>循环总次数</th>
</tr>
{/if}
<tr>
<td>
{$value}
</td>
<td>
{$value@key}
</td>
<td>
{$value@index}
</td>
<td>
{$value@iteration}
</td>
<td>
{$value@first}
</td>
<td>
{$value@last}
</td>
<td>
{if $value@last} {$value@total} {/if}
</td>
</tr>
{/foreach}
</table>
浏览器渲染结果
name= 随便命名
loop= 最后一个循还号
start= 起点
step= 跳的值的个数
max= 最大输出几个值
show=
PHP页面:
<?php
// 引入Smarty类
include_once('./Smart/libs/Smarty.class.php');
// 实例化Smarty类对象
$smarty = new Smarty();
// 设置Smarty的视图文件根目录
$smarty->setTemplateDir('./view');
// 创建一个枚举数组
$stu_info = array(10010, '张三', '男', 24, 6000, 300);
// 使用Smarty对变量赋值
$smarty->assign('stu_info', $stu_info);
// 引入前端展示文件
$smarty->display('./demo.html');
HTML前端展示页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{section name='i' loop=$stu_info} {$stu_info[i]} {/section}
</body>
</html>
PHP页面:
<?php
// 引入Smarty类
include_once('./Smart/libs/Smarty.class.php');
// 实例化Smarty类对象
$smarty = new Smarty();
// 设置Smarty的视图文件根目录
$smarty->setTemplateDir('./view');
//创建一个二维数组
$stu_info = array(
array(10010, '张三', '男', 24, 6000, 300),
array(10020, '李四', '女', 28, 9000, 200),
array(10030, '周五', '男', 29, 12000, 340),
array(10040, '陆六', '女', 26, 9800, 230)
);
// 使用Smarty对变量赋值
$smarty->assign('stu_info', $stu_info);
// 引入前端展示文件
$smarty->display('./demo.html');
HTML前端展示页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{section name='i' loop=$stu_info}
{section name='k' loop=$stu_info[i]}
{$stu_info[i][k]}
{/section}
{/section}
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{section name='i' loop=$stu_info start=2 step=2 max=4}
{section name='k' loop=$stu_info[i]}
{$stu_info[i][k]}
{/section}
{/section}
</body>
</html>
meaning | translate | example | |
---|---|---|---|
eq | equal | 相等 | {if count eq 1}{/if} |
ne / neq | not equal | 不相等 | {if count ne 0 && name eq "lucy"}{/if} |
gt | greater than | 大于 | {if count gt 1}{/if} |
lt | less than | 小于 | {if count lt 10}{/if} |
gte / ge | great than or equal | 大于等于 | {if count ge 1}{/if} |
let / le | less than or equal | 小于等于 | {if count le 10}{/if} |
mod | module | 求模 | {if count eq 1}{/if} |
not | not | 非 | |
X is [not] div by Y | divisible | 整除 | {if count is div by 20}{/if} |
X is [not] even | even | X [不] 是偶数 | {if count1 is even}{/if} |
X is [not] even by Y | even | (X/Y)%2 (!=) == 0 | {if count1 is even by count2}{/if} |
X is [not] odd | odd number | X [不] 是奇数 | {if count2 is odd}{/if} |
X is [not] odd by Y | odd number | (X/Y)%2 (==) != 0 | {if count1 is odd by count2}{/if} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Smarty模板引擎</title>
<style type="text/css">
body{background-color: #99ff00;}
</style>
</head>
<body>
<h2>判断当兵的年龄</h2>
<{if $smarty.get.age gte 18 and $smarty.get.age lte 23}>
<font color='blue'>你符合当兵的年龄要求!</font>
<{else}>
<font color='red'>你干嘛干嘛去!</font>
<{/if}>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Smarty模板引擎</title>
</head>
<body>
<h2>表格隔行变色</h2>
<table border="1" width="500">
<tr bgcolor=#f0f0f0>
<th>编号</th>
<th>新闻标题</th>
<th>发布时间</th>
</tr>
<{foreach $arr as $value}>
<{if $value@iteration is div by 3}>
<tr bgcolor='#99ff00'>
<{else}>
<tr>
<{/if}>
<td> </td>
<td> </td>
<td> </td>
</tr>
<{/foreach}>
</table>
举例
调节器 | 含义 | PHP函数 | 示例演示 | |
---|---|---|---|---|
upper | 将变量值转成大写字母。 | strtoupper() | {$title\ | upper} |
lower | 将变量值转成小写字母 | strtolower() | {$title\ | lower} |
capitalize | 每个单词的第一个字母大写 | ucwords() | {$title\ | capitalize} |
nl2br | 将变量中"\n"回车 全部转换成HTML的 <br /> | nl2br() | {$title\ | nl2br} |
replace | 对变量进行简单的查找和替换 | str_replace() | {$title\ | replace:’a’:’b’} |
date_format | 将日期和时间格式化成strftime()的格式。 | strftime() | {$time\ | date_format:%Y-%m-%d} |
truncate | 截取字符串到指定长度,默认长度是80 | substr() | {$title\ | truncate:80:’…’} |
----- END -----