Home >Backend Development >PHP Tutorial >How smarty template engine gets data from php, smarty template_PHP tutorial
The example in this article describes how the smarty template engine obtains data from php. Share it with everyone for your reference. The details are as follows:
Smarty can assign ($smarty->assign) variable types: all data types supported by PHP - basic data types, composite data types, special data types (see smarty related manuals for details).
Operation/display file: index.php
$arr2 = array("city1"=>"Beijing","city2"=>"Shanghai","city3"=>"Guangzhou");//Associative array
$smarty->assign("arr2",$arr2);//Assign associative array
$arr3 = array(array("Beijing","Shanghai","Guangzhou"),array("Guan Yu","Zhang Fei","Beauty"));
$smarty->assign("arr3",$arr3);
$arr4 = array("aa"=>array("Beijing","Shanghai","Guangzhou"),"bb"=>array("Guan Yu","Zhang Fei","Beauty") );
$smarty->assign("arr4",$arr4);
//Object type
class Master{
public $name;
public $address;
}
$master = new Master();
$master->name="Baidu";
$master->address = "Zhongguancun";
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("puppy",4,"golden",$arr2);
$dog->master = $master;
$smarty->assign("dog",$dog);
$smarty->display("index.tpl");
?>
Template file: index.tpl
Get string: {$aa}
Take an integer: {$bb}
Take floating point type: {$cc}
Take Boolean value: {$dd}
Get array (index array): {$arr1[0]}--{$arr1[1]}--{$arr1[2]}
Get array (associative array): {$arr2.city1}--{$arr2.city2}--{$arr2.city3}
Get two sets of arrays (index, take a single): {$arr3[0][0]}
Get two sets of arrays (index, traverse all):
Get a two-dimensional array (association): {$arr4.aa[2]}
Get a two-dimensional array (association, traversal):
Get the object (common attributes): {$dog->name}
Get the object (array attribute): {$dog->arr.city1}
Get the object (object attribute): {$dog->master->name}
I hope this article will be helpful to everyone’s PHP programming design.