摘要:本章节主要学习smarty模板的下载、导入、引用,并学习smarty模板常见数据类型的渲染输出。通过本章节的学习,实现了将模板数据渲染出一个表格,代码如下:<?php require __DIR__.'/config/config.php'; //表格名称 $tableName='日本女演员'; $smarty->assign('t
本章节主要学习smarty模板的下载、导入、引用,并学习smarty模板常见数据类型的渲染输出。通过本章节的学习,实现了将模板数据渲染出一个表格,代码如下:
<?php
require __DIR__.'/config/config.php';
//表格名称
$tableName='日本女演员';
$smarty->assign('tableName',$tableName);
//标题
$arrTitle=['编号','姓名','胸围','年龄'];
$smarty->assign('arrTitle',$arrTitle);
//表格内容
$arrContents=[
['id'=>1,'name'=>'松岛枫','weight'=>95,'age'=>35],
['id'=>2,'name'=>'麻生希','weight'=>93,'age'=>28],
['id'=>3,'name'=>'小泽玛利亚','weight'=>98,'age'=>36],
['id'=>4,'name'=>'波多野结衣','weight'=>99,'age'=>30]
];
$smarty->assign('arrContents',$arrContents);
//提供者
const PROVIDER='1Pong';
class Footer
{
public $contents = '更多精彩内容,请百度搜索';
public function show()
{
echo '内容仅供参考,' . $this->contents;
}
}
$footer=new Footer();
$smarty->assign('footer',$footer);
$smarty->display(__DIR__.'/temp/showTable.html');config.php
<?php
require __DIR__.'/../vendor/autoload.php';
//创建smarty模板对象
$smarty=new Smarty();
//配置目录
$smarty->setTemplateDir(__DIR__ . '/../temp'); //模板目录
$smarty->setCompileDir(__DIR__.'/../temp_c'); //编译目录
$smarty->setCacheDir(__DIR__.'/../cache'); //缓存目录
$smarty->setConfigDir(__DIR__.'/../config'); //配置目录
//配置定界符:可选
$smarty -> setLeftDelimiter('{'); //变量左定界符
$smarty -> setRightDelimiter('}'); //变量右定界符
//配置缓存:可选
$smarty ->setCaching(false); //关闭缓存
$smarty->setCacheLifetime(60*60*24); //缓存有效时间showTable.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{$tableName}</title>
<style>
table
{
text-align: center;
}
div:nth-child(1)
{
width: 100%;
}
div:nth-child(2)
{
width: 60%;
margin: 50px auto;
}
</style>
</head>
<body>
<table border="1" cellpadding="5" cellspacing="0" align="center" width="60%">
<caption><h2>{$tableName}</h2></caption>
<tr bgcolor="#add8e6">
{foreach $arrTitle as $value}
<th>{$value}</th>
{/foreach}
</tr>
{foreach $arrContents as $value}
<tr>
<td>{$value.id}</td>
<td>{$value.name}</td>
<td>{$value.weight}</td>
<td>{$value.age}</td>
</tr>
{/foreach}
</table>
<div>
<div>
<p>数据提供者:{$smarty.const.PROVIDER}。{$footer->show()}。</p>
</div>
</div>
</body>
</html>效果如下:

批改老师:天蓬老师批改时间:2019-01-18 10:48:18
老师总结:模板语法是将部分常用的php代码进行封装, 本质上, 模板的文件格式仍是php, 尽管你看到的是html