生活随笔
收集整理的這篇文章主要介紹了
Smarty中的变量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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中的函數、屬性、注釋*}>?? hello,<{$name}>!?? <{else}>?? hello,world!?? <{/if}>??
如果是分配的數組和對象,也可以在smarty中訪問
例:數組
[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}>??
運行結果:
例:對象
[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}>??
運行結果:300px 200px
2、配置文件中的變量
使用配置文件中的變量可以通過兩個"#"或者smarty中的保留變量$smarty.config.來調用
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#",否則會當作字符串處理?*}>?? age:<{"`$smarty.config.age`"}><br>?? address:<{#address#}><br>??
運行結果:
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當前時間
[html]?view plaincopy print?
<{$smarty.now}><{*返回當前時間的時間戳*}><br>?? <{$smarty.now|date_format:"%Y-%m-%d?%H:%M:%S"}><{*格式化輸出當前時間*}><br>??
? ?運行結果:?
? ? 3.3、$smarty.const.常量名
$smarty.const.常量名直接調用PHP中的常量名,不需要assign
[php]?view plaincopy print?
define('CONST_STR','chuang');??
[html]?view plaincopy print?
<{$smarty.const.CONST_STR}>??
運行結果: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}>之間的內容會放到一個變量中去,name=“變量名”,默認為default
運行結果:
? ? 3.5、$smarty.config.變量名
$smarty.config.變量名,可以獲取配置文件中的變量的值,在 2 中已有使用
? ? 3.6、$smarty.section ? ? ? $smarty.foreach
用在section和foreach循環遍歷中
? ? 3.7、$smarty.template
返回本模板的文件名
總結
以上是生活随笔為你收集整理的Smarty中的变量的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。