smarty模板引擎從php中獲取數(shù)據(jù)的方法
本文實例講述了smarty模板引擎從php中獲取數(shù)據(jù)的方法。分享給大家供大家參考。具體如下:
smarty可以分配($smarty->assign)的變量類型:所有php支持的數(shù)據(jù)類型——基本數(shù)據(jù)類型、復合數(shù)據(jù)類型、特殊數(shù)據(jù)類型(具體見smarty相關手冊)。
操作/顯示文件: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"=>"廣州");//關聯(lián)數(shù)組
$smarty->assign("arr2",$arr2);//分配關聯(lián)數(shù)組
$arr3 = array(array("北京","上海","廣州"),array("關羽","張飛","美女"));
$smarty->assign("arr3",$arr3);
$arr4 = array("aa"=>array("北京","上海","廣州"),"bb"=>array("關羽","張飛","美女"));
$smarty->assign("arr4",$arr4);
//對象類型
class Master{
public $name;
public $address;
}
$master = new Master();
$master->name="百度";
$master->address = "中關村";
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ù)組(關聯(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ù)組(關聯(lián)):{$arr4.aa[2]}</p>
<p style="color:blue;">取二維數(shù)組(關聯(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程序設計有所幫助。
相關文章
php post json參數(shù)的傳遞和接收處理方法
今天小編就為大家分享一篇php post json參數(shù)的傳遞和接收處理方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05Codeigniter實現(xiàn)處理用戶登錄驗證后的URL跳轉
這篇文章主要介紹了Codeigniter實現(xiàn)處理用戶登錄驗證后的URL跳轉,需要的朋友可以參考下2014-06-06Symfony2使用Doctrine進行數(shù)據(jù)庫查詢方法實例總結
這篇文章主要介紹了Symfony2使用Doctrine進行數(shù)據(jù)庫查詢方法,結合實例形式總結分析了基于Doctrine的基本查詢、DQL及查詢生成器的基本實現(xiàn)方法,需要的朋友可以參考下2016-03-03