程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> smarty模板引擎從php中獲取數據的方法

smarty模板引擎從php中獲取數據的方法

編輯:PHP綜合

本文實例講述了smarty模板引擎從php中獲取數據的方法。分享給大家供大家參考。具體如下:

smarty可以分配($smarty->assign)的變量類型:所有php支持的數據類型——基本數據類型、復合數據類型、特殊數據類型(具體見smarty相關手冊)。

操作/顯示文件:index.php
復制代碼 代碼如下:<?php
//創建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);//分配字符串
//分配數組,數組一般從數據庫取出,這裡直接給數組
$arr1 = array("北京","上海","廣州");//索引數組
$smarty->assign("arr1",$arr1);//分配索引數組

$arr2 = array("city1"=>"北京","city2"=>"上海","city3"=>"廣州");//關聯數組
$smarty->assign("arr2",$arr2);//分配關聯數組

$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
復制代碼 代碼如下:<html>
<h2>smarty變量操作</h2>
<p style="color:green;">取字符串:{$aa}</p>
<p style="color:red;">取整數:{$bb}</p>
<p style="color:blue;">取浮點型:{$cc}</p>
<p style="color:orange;">取布爾值:{$dd}</p>
<p style="color:indigo;">取數組(索引數組):{$arr1[0]}--{$arr1[1]}--{$arr1[2]}</p>
<p style="color:green;">取數組(關聯數組):{$arr2.city1}--{$arr2.city2}--{$arr2.city3}</p>
<p style="color:red;">取二組數組(索引,取單個):{$arr3[0][0]}</p>
<p style="color:red;">取二組數組(索引,遍歷全部):</p>
<p style="color:blue;">取二維數組(關聯):{$arr4.aa[2]}</p>
<p style="color:blue;">取二維數組(關聯、遍歷):</p>
<p style="color:orange;">取對象(普通屬性):{$dog->name}</p>
<p style="color:orange;">取對象(數組屬性):{$dog->arr.city1}</p>
<p style="color:orange;">取對象(對象屬性):{$dog->master->name}</p>
</html>

希望本文所述對大家的php程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved