>php教程 >php手册 >smarty模板引擎从php中获取数据的方法

smarty模板引擎从php中获取数据的方法

WBOY
WBOY원래의
2016-06-06 20:12:55817검색

这篇文章主要介绍了smarty模板引擎从php中获取数据的方法,涉及smarty变量与php代码的混编技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了php/20141105125967.html">smarty模板引擎从php中获取数据的方法。分享给大家供大家参考。具体如下:

smarty可以分配($smarty->assign)的变量类型:所有php支持的数据类型——基本数据类型、复合数据类型、特殊数据类型(具体见smarty相关手册)。

操作/显示文件:index.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

复制代码 代码如下:


smarty变量操作


取字符串:{$aa}


取整数:{$bb}


取浮点型:{$cc}


取布尔值:{$dd}


取数组(索引数组):{$arr1[0]}--{$arr1[1]}--{$arr1[2]}


取数组(关联数组):{$arr2.city1}--{$arr2.city2}--{$arr2.city3}


取二组数组(索引,,取单个):{$arr3[0][0]}


取二组数组(索引,遍历全部):


取二维数组(关联):{$arr4.aa[2]}


取二维数组(关联、遍历):


取对象(普通属性):{$dog->name}


取对象(数组属性):{$dog->arr.city1}


取对象(对象属性):{$dog->master->name}


希望本文所述对大家的php程序设计有所帮助。

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.