smarty訪問數組中的數據,如果是關聯數組直接用點.


$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

9.在模板文件中使用圖片、css文件、js文件時,路徑要以訪問的php文件(如;index.php)路徑為主,因為我們訪問的是php文件,而模板文件 (如:index.tpl)是被包含在php文件中的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM