smarty模板入门

smarty模板在当前的php项目开发过程中运用非常广泛,若能熟练掌握smarty模板的使用,那么对于MVC模型会更深的体会与理解(不理解什么是MVC模型的,可以到如何理解MVC模型这篇文章看看!)。
1.下载并配置smarty
下载smarty的最新版,解压,拷贝其中的libs文件夹到项目中。下载地址:http://www.xpgod.com/soft/5937.html

2.在项目中创建templates、templates_c、cache、config四个文件夹
在项目中创建index.php,代码如下
<?php
require_once("libs/smarty.class.php");
$smarty=new smarty();
$smarty->template_dir="templates";//指定模板文件的路径
$smarty->compile_dir="templates_c";//指定编译的文件路径
$smarty->cache_dir="cache";//指定缓存文件路径
$smarty->config_dir="config";//指定smarty配置文件路径
$smarty->left_delimiter="<{";//指定左定界符,避免和JS冲突
$smarty->right_delimiter="}>";
$smarty->assign("name","天涯的海风");//注册变量
$smarty->display("index.tpl");//显示模板
?>
接下来,在templates文件夹下创建.tpl的模板文件,显示变量值
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>欢迎您:<{$name}></title>
</head>

<body>
</body>
</html>

3.if条件控制
PHP页面代码:
$temp=1;
$smarty->assign("temp",$temp);
模板前台:
<{if $temp gt 0}>
临时变量>0
<{else}>
临时变量<=0
<{/if}>
其中
eq 判断是否相等
neq、ne 不相等
lt 小于
lte 小于等于
gt 大于
gte 大于等于
is div by 被某数整除
is even 为偶数
is odd 为奇数

4.循环
$arr=array(1,2,3);
$smarty->assign("arr",$arr);

<{foreach from=$arr item=v key=k}>
 键:<{$k}>|值:<{$v}>
<{foreachelse}>     <{*smarty注释,数组为空时可以显示对应内容*}>
 数组为空
<{/foreach}>

<{section name=k loop=$arr}>  <{*不支持引用数组*}>
 值:<{$arr[k]}>&nbsp;
 <{sectionelse}>
 数组为空
<{/section}>

5.smarty配置文件
(1)在config文件夹下创建smarty.conf文件,内容如下
#全局变量
title="欢迎进入海风网站"

#节点变量
[section1]
title="下节页面"

(2)在templates下创建header.tpl页面
<{config_load file="smarty.conf"}>  <{*引入配置文件*}>
<html>
<head>
<title><{$smarty.config.title}>或者<{#title#}></title>
</head>

<body>
</body>
</html>
在项目文件下创建后台代码并显示,即可看到全局变量配置的效果

(3)页面包含,并显示子节点
承接上面的例子,修改index.tpl为以下内容
<{include file="header.tpl"}>    <{*包含头部已经制作好的页面*}>
<{config_load file="smarty.conf" section="section1"}>  <{*加载配置文件,指定访问子节点*}>
显示子节点值:<{#title#}> 或者 <{$smarty.config.title}>

最终在页面头部标题显示为全部配置文件中的 欢迎进入海风网站
而在页面主体部分则只会显示子节点中  下面的页面节点

(4)模板修饰符
<{$name|capitalize}>   <{*每个单词的首字母大写*}>
$smarty->assign("b","<b>haifeng</b>");//正常显示HTML标签表过
<{$b|strip_tags}>     <{*消除HTML标签效果*}>
<{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}>   <{*日期格式化*}>

(5)缓存与更新
$smarty->caching=true;//开启缓存
$smarty->cache_lifetime=5;//缓存时间为5秒

在后台页面中创建函数,著名函数名
function insert_gettime(){
 return date("Y-m-d H:i:s",time()+8*3600);   //必须要有返回值
}
在前台调用的过程中会发现以下2中方式的区别:
<{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}>   <{*缓存日期格式*}>
<{insert name="gettime"}>                <{*不缓存日期格式调用*}>

(6)读取结果集并显示的例子
PHP代码
$result=$mysql->execute("select * from something");
while($row=mysql_fetch_array($result)){
 $arr1[]=$row;
}
$smarty->assign("arr1",$arr1);
前台读取,.后面是字段名
<{foreach from=$arr1 item=v}>
 <{$v.Sid}>&nbsp;
<{/foreach}>

(7)smarty调试
$smarty->debugging=true;


(8)页面切割与合成
<{include_php file="header.php"}>


(9)普通for循环

<{section name=loop loop=$count} >
id: <{$smarty.section.loop.index} >
<{/section}>

(10)自定义变量

<{assign var="site" value=$v.RightName}>

取值<{$site}>

原文地址:https://www.cnblogs.com/sontan/p/7446476.html