smarty模板引擎從php中獲取數(shù)據(jù)的方法
本文實例講述了smarty模板引擎從php中獲取數(shù)據(jù)的方法。分享給大家供大家參考。具體如下:
smarty可以分配($smarty->assign)的變量類型:所有php支持的數(shù)據(jù)類型——基本數(shù)據(jù)類型、復(fù)合數(shù)據(jù)類型、特殊數(shù)據(jù)類型(具體見smarty相關(guān)手冊)。
操作/顯示文件:index.php
//創(chuàng)建smarty對象
require_once("./libs/Smarty.class.php");
$smarty = new Smarty();
$smarty->assign("aa","hello word");//分配字符串
$smarty->assign("bb",123);//分配整型
$smarty->assign("cc",90.8);//分配float型,浮點型
$smarty->assign("dd",true);//分配字符串
//分配數(shù)組,數(shù)組一般從數(shù)據(jù)庫取出,這里直接給數(shù)組
$arr1 = array("北京","上海","廣州");//索引數(shù)組
$smarty->assign("arr1",$arr1);//分配索引數(shù)組
$arr2 = array("city1"=>"北京","city2"=>"上海","city3"=>"廣州");//關(guān)聯(lián)數(shù)組
$smarty->assign("arr2",$arr2);//分配關(guān)聯(lián)數(shù)組
$arr3 = array(array("北京","上海","廣州"),array("關(guān)羽","張飛","美女"));
$smarty->assign("arr3",$arr3);
$arr4 = array("aa"=>array("北京","上海","廣州"),"bb"=>array("關(guān)羽","張飛","美女"));
$smarty->assign("arr4",$arr4);
//對象類型
class Master{
public $name;
public $address;
}
$master = new Master();
$master->name="百度";
$master->address = "中關(guān)村";
class Dog{
public $name;
public $age;
public $color;
public $arr;
public $master;
function __construct($name,$age,$color,$arr){
$this->name = $name;
$this->age = $age;
$this->color = $color;
$this->arr = $arr;
}
}
$dog = new Dog("小狗",4,"金黃色",$arr2);
$dog->master = $master;
$smarty->assign("dog",$dog);
$smarty->display("index.tpl");
?>
模板文件:index.tpl
<h2>smarty變量操作</h2>
<p style="color:green;">取字符串:{$aa}</p>
<p style="color:red;">取整數(shù):{$bb}</p>
<p style="color:blue;">取浮點型:{$cc}</p>
<p style="color:orange;">取布爾值:{$dd}</p>
<p style="color:indigo;">取數(shù)組(索引數(shù)組):{$arr1[0]}--{$arr1[1]}--{$arr1[2]}</p>
<p style="color:green;">取數(shù)組(關(guān)聯(lián)數(shù)組):{$arr2.city1}--{$arr2.city2}--{$arr2.city3}</p>
<p style="color:red;">取二組數(shù)組(索引,取單個):{$arr3[0][0]}</p>
<p style="color:red;">取二組數(shù)組(索引,遍歷全部):</p>
<p style="color:blue;">取二維數(shù)組(關(guān)聯(lián)):{$arr4.aa[2]}</p>
<p style="color:blue;">取二維數(shù)組(關(guān)聯(lián)、遍歷):</p>
<p style="color:orange;">取對象(普通屬性):{$dog->name}</p>
<p style="color:orange;">取對象(數(shù)組屬性):{$dog->arr.city1}</p>
<p style="color:orange;">取對象(對象屬性):{$dog->master->name}</p>
</html>
希望本文所述對大家的php程序設(shè)計有所幫助。
相關(guān)文章
php實例分享之通過遞歸實現(xiàn)刪除目錄下的所有文件詳解
最近遇到一個實際問題,需要清空制定目錄下的所有文件及清空數(shù)據(jù)庫。清空數(shù)據(jù)庫不難,但要如何遞歸刪除一個目錄下的所有文件呢。 于是去網(wǎng)上研究了下資料再加上自己琢磨解決了這一問題。2014-05-05
Laravel Eloquent分表方法并使用模型關(guān)聯(lián)的實現(xiàn)
這篇文章主要介紹了Laravel Eloquent分表方法并使用模型關(guān)聯(lián)的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11

