Smarty模板技術/引擎——變數操作(2)

來源:互聯網
上載者:User

標籤:

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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.