php使用Smarty的相關注意事項及訪問變數的幾種方式

來源:互聯網
上載者:User

$tpl=new Smarty();//建立一個smarty對象,我使用的是Smarty-3.1.6版本
1.設定smarty模板路徑$tpl->setTemplateDir();預設情況下是templates
2.設定smarty模板編譯路徑$tpl->setCompileDir();預設情況下是templates_c
3.設定smarty模板引擎的左右 分隔字元,

$tpl->left_delimiter="<{";

$tpl->right_delimiter="}>";

預設情況下:public $left_delimiter = "{";//smarty原始碼

public $right_delimiter = "}";//smarty原始碼

為什麼我們要改這些分隔字元?

  因為比如在較早版本smarty引擎模板中,會報錯,不能自動識別。
比如:
<style>
div{margin:0;}
</style>
或者 javascript中

複製代碼 代碼如下:<script>
function show(){
alert("smarty");
}
</script>

這兩種情況下,都有“左右大括弧”,smarty引擎碰到會報錯
4.初始化操作我們可以在外部另外建立一個初始化操作的php檔案,如:smarty.ini.php。然後在php檔案中包括進來即可 複製代碼 代碼如下:<?php
include "../Smarty3.1.6/libs/Smarty.class.php";
$tpl=new Smarty();
$tpl->setTemplateDir("./Tpl");
$tpl->setTemplateDir("./Compile");
$tpl->left_delimiter="<{";
$tpl->right_delimiter="}>";
?>

5.使用smarty模板引擎的display函數或者include其他模板時,都得以smarty對象中指定的模板目錄(比如:Tpl目錄,預設是templates目錄)為基目錄。
  ①模板目錄是:Tpl,該目錄下存放著很多模板,有default,green,red模板,default模板目錄下有很多模板檔案(index.tpl、header.tpl、footer.tpl),此時display的正確用法:$tpl->display(“default/index.tpl”);即基目錄下的default模板目錄
  ②在模板檔案(如:index.tpl)中包含其他模板檔案時(如:header.tpl、footer.tpl),include的正確寫法應該是:<{include “default/header.tpl”}> 、<{include “default/footer.tpl”}>
  雖然index.tpl、header.tpl、footer.tpl都在同一個目錄下,但是<{include “header.tpl”}> 、<{include “footer.tpl”}>是錯誤的寫法,這種情況,smarty引擎會到Tpl目錄下找header和footer,而不是在default下面尋找
6.如果要想讓各個目錄下的PHP程式都可以載入Smarty和使用Smarty指定的模板目錄和編譯目錄,唯一的辦法是使用絕對路徑。
7.Smarty模板引擎中訪問變數的方式(模板中的變數前記得加”$”符號)
①訪問數組
索引數組:
   $tpl->assign("arr",array("aa","bb","cc"));
   $tpl->assign("arr2",array(array("二維數組一一","二維數組一二"),array("二維數組二一","二維數組二二")));
     訪問索引數組:<{ $arr[0] }>、<{ $arr[0] }>、<{ $arr[0] }>
   訪問二維索引數組:<{ $arr2[0][0] }>、<{ $arr2[0][1] }>
關聯陣列:(使用 . 符號來訪問)
   訪問關聯陣列:<{$arr3.id}>、<{$arr3.name}>、<{$arr3.age}>
②訪問對象
建立對象:   複製代碼 代碼如下: 
class human{
private $sex;
private $name;
private $age;
public function __construct($s,$n,$a){
$this->sex=$s;
$this->name=$n;
$this->age=$a;
}
public function print_info(){
return $this->sex."--".$this->name."--".$this->age;
}
}
$tpl->assign("student",new human("male","MarcoFly",22));

給模板中的對象賦值:<{$student->print_info()}>
8.Smarty模板引擎中的數學運算可以應用到模板變數中
給變數賦值
    $tpl->assign("num1",10);
    $tpl->assign("num2",5.5);
模板變數輸出
    <{$num1}> //結果10
    <{$num2}> //結果5.5
    <{$num1+$num2}> //結果15.5
    <{$num1+$num2*$num2/$num1}>//結果13.025
原創文章
轉載請註明:WEB開發_小飛

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.