標籤:
1, 變數的分類
① 從PHP中分配的變數,比如a.php跳轉到b.php時候,可以在a.php中分配變數,b.tpl中直接調用。a.php中代碼,$smarty->assign(‘str’,’hello world’);在b.tpl中代碼,{$str}直接列印出hello world。
index.php
<?phprequire_once "./libs/Smarty.class.php";$smarty = new Smarty();$smarty->assign(‘str‘,‘hello world‘);$smarty->display(‘index.tpl‘);
index.tpl
html><body><h1>顯示記錄</h1>{$str}<br/></body></html>
② 從設定檔中讀取變數
在項目下建立config目錄,config目錄下面建立設定檔my.ini。
my.ini
title = ‘smarty顯示記錄‘bgcolor = ‘pink‘
index.php
<?phprequire_once "./libs/Smarty.class.php";$smarty = new Smarty();$smarty->assign(‘str‘,‘hello world‘);$smarty->display(‘index.tpl‘);?>
index.tpl
{config_load file="./config/my.ini"}<html><body bgcolor="{#bgcolor#}"><h1>顯示記錄</h1>{#title#}<br/></body></html>
頁面列印結果
在建立smarty對象後,可以指定設定檔路徑,tpl中直接引用即可。
index.php修改為如下樣式:
<?phprequire_once "./libs/Smarty.class.php";$smarty = new Smarty();$smarty->config_dir = ‘./config‘;$smarty->assign(‘str‘,‘hello world‘);$smarty->display(‘index.tpl‘);?>
index.tpl樣式如下:
{config_load file="my.ini"}<html><body bgcolor="{#bgcolor#}"><h1>顯示記錄</h1>{#title#}<br/></body></html>
③ Smarty保留變數,在tpl中直接擷取get、post、server、session變數。我們通常是在php中擷取這些變數,再通過smarty的assign屬性發送給tpl。現在通過smarty的保留變數可以直接tpl中擷取這些變數,當然我們不提倡這麼做。
login.php跳轉到index.php,index.php通過smarty模板顯示。
login.php
<a href="index.php?name=hello world& age=20">新頁面</a>
a) 舊方式
index.php
<?phprequire_once "./libs/Smarty.class.php";$smarty = new Smarty();$smarty->assign(‘name‘,$_GET[‘name‘]);$smarty->assign(‘age‘,$_GET[‘age‘]);$smarty->display(‘index.tpl‘);
index.tpl
<html><body bgcolor="pink"><h1>顯示記錄</h1>{$name}<br/>{$age}<br/></body></html>
b 新方式
index.php
<?phprequire_once "./libs/Smarty.class.php";$smarty = new Smarty();$smarty->display(‘index.tpl‘);?>
index.tpl
<html><body bgcolor="pink"><h1>顯示記錄</h1>{$smarty.get.name}<br/>{$smarty.get.age}<br/></body></html>
兩者輸出結果一樣,建議使用舊的方式。
2,在模板檔案中對引用的變數可以進行數學運算,但不能使用()改變運算的次序。
Smarty的變數調節器,就是操作變數的函數,在tpl中引用的方式{變數調節器|字串},比如{$title|capitalize}字串每個單字首大寫。我們可以自建函數,操作變數。
Smarty模板技術/引擎——變數操作(2)