生活随笔
收集整理的這篇文章主要介紹了
Smarty中的变量
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Smarty中變量分為三類
1、PHP分配的變量
index.php
[php]?view plaincopy print?
require('./include.php');????? ?? $smarty->assign('name','chuangrain');?????? ?? $smarty->display('index.html');????????
index.html
[html]?view plaincopy print?
<{if?$name?==?'chuangrain'}><{*?Smarty中的函數(shù)、屬性、注釋*}>?? hello,<{$name}>!?? <{else}>?? hello,world!?? <{/if}>??
如果是分配的數(shù)組和對(duì)象,也可以在smarty中訪問(wèn)
例:數(shù)組
[php]?view plaincopy print?
$arr1?=?array('趙','錢','孫',array('楊','孔'));?? ?? $arr2?=?array(?? ????'zhou'?=>?'周',?? ????'zhang'?=>?'張',?? ????'wang'?=>?'王',?? ????'li'?=>?array(?? ????????'chen'?=>?'陳',?? ????????'xiang'?=>?'向',?? ????),?? );?? ?? $smarty->assign('arr1',$arr1);?? $smarty->assign('arr2',$arr2);??
[html]?view plaincopy print?
<{$arr1.0}>?? <{$arr1[1]}>?? <{$arr1.2}>?? <{$arr1.3.0}>?? <{$arr1.3[1]}>?? <br>?? <{$arr2.zhou}>?? <{$arr2.zhang}>?? <{$arr2.wang}>?? <{$arr2.li.chen}>?? <{$arr2.li.xiang}>??
運(yùn)行結(jié)果:
例:對(duì)象
[php]?view plaincopy print?
class?pic?{?? ????public?$height?=?'300px';?? ????public?$width?=?'200px';?? }?? ?? $p?=?new?pic();?? ?? $smarty->assign('p',$p);??
[html]?view plaincopy print?
<{$p->height}>?? <{$p->width}>??
運(yùn)行結(jié)果:300px 200px
2、配置文件中的變量
使用配置文件中的變量可以通過(guò)兩個(gè)"#"或者smarty中的保留變量$smarty.config.來(lái)調(diào)用
info.conf
[plain]?view plaincopy print?
name?=?"chuangrain"?? age?=?20?? address?=?"四川"??
html
[html]?view plaincopy print?
<{config_load?file="info.conf"}><{*?加載配置文件中的info.conf?*}>?? name:<{#name#}><br><{*?不能將#name#寫為"#name#",否則會(huì)當(dāng)作字符串處理?*}>?? age:<{"`$smarty.config.age`"}><br>?? address:<{#address#}><br>??
運(yùn)行結(jié)果:
3、smarty保留的變量
? ? 3.1、request變量
$smarty.get.變量名,可以獲取url中變量的值(用得比較多)
$smarty.post.var ? ??$smarty.cookies.var ? ?$smarty.server.var ? ?$smarty.env.var ? ? ?$smarty.session.var ? ? ??$smarty.request.var
? ? 3.2、$smarty.now當(dāng)前時(shí)間
[html]?view plaincopy print?
<{$smarty.now}><{*返回當(dāng)前時(shí)間的時(shí)間戳*}><br>?? <{$smarty.now|date_format:"%Y-%m-%d?%H:%M:%S"}><{*格式化輸出當(dāng)前時(shí)間*}><br>??
? ?運(yùn)行結(jié)果:?
? ? 3.3、$smarty.const.常量名
$smarty.const.常量名直接調(diào)用PHP中的常量名,不需要assign
[php]?view plaincopy print?
define('CONST_STR','chuang');??
[html]?view plaincopy print?
<{$smarty.const.CONST_STR}>??
運(yùn)行結(jié)果:chuang
? ? 3.4、$smarty.capture
1.html
[html]?view plaincopy print?
<a?href="#">aaaaaaaaaaaaaaaaaa</a>??
[html]?view plaincopy print?
<{capture?name=str}>?? <{include?file="1.html"}>?? <{/capture}>?? <{if?$smarty.capture.str}>?? ????<center><h1><{$smarty.capture.str}></h1><center>?? <{/if}>??
<{capture}><{/capture}>之間的內(nèi)容會(huì)放到一個(gè)變量中去,name=“變量名”,默認(rèn)為default
運(yùn)行結(jié)果:
? ? 3.5、$smarty.config.變量名
$smarty.config.變量名,可以獲取配置文件中的變量的值,在 2 中已有使用
? ? 3.6、$smarty.section ? ? ? $smarty.foreach
用在section和foreach循環(huán)遍歷中
? ? 3.7、$smarty.template
返回本模板的文件名
總結(jié)
以上是生活随笔為你收集整理的Smarty中的变量的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。