<?php // Smarty配置文件 // 使用Composer安装的Smarty 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');
渲染模板
<?php // 开启session session_start(); // 加载Smarty require __DIR__ . '/config/config.php'; // 1. 显示单值变量 : 标量 $name = '皮卡丘'; // 模板赋值 $smarty->assign('name', $name); // 2. 数组:索引数组 $course = ['火焰鸟', '急冻鸟', '闪电鸟', '炎帝', '水君']; $smarty->assign('course', $course); // 3. 数组:关联数组 $godBird = ['name' => '闪电鸟', 'gift' => '麻痹', 'kill' => '十万伏特']; $smarty->assign('godBird', $godBird); // 4. 数组:多维数组 $godBirds[] = ['name' => '闪电鸟', 'gift' => '麻痹', 'kill' => '十万伏特']; $godBirds[] = ['name' => '火焰鸟', 'gift' => '不灭', 'kill' => '喷射火焰']; $godBirds[] = ['name' => '急冻鸟', 'gift' => '清醒', 'kill' => '急冻光线']; $smarty->assign('godBirds', $godBirds); // 5. 对象 class Test { public $name = '神奇宝贝世界'; public function welcome() { return '欢迎来到' . $this->name; } } $test = new Test(); $smarty->assign('test', $test); // 6. 自定义函数 function add($a, $b) { return $a + $b; } // 7. 常量,不需要赋值,直接在模板中输出 const SITE_NAME = '神奇宝贝中心,五秒回血'; // 8. 系统常量,不需要赋值,直接在模板中输出 $_POST['user_name'] = '乔伊小姐'; $_GET['page'] = 10; $_SESSION['pass'] = sha1('123456'); // 模板渲染 $smarty->display('demo03.html');
模板
{* 显示变量 *} <h2>就决定是你了:{$name}</h2> <h2>就决定是你了:{" $name "}</h2> {* 显示索引数组 *} <p>三圣鸟 : {$course.0},{$course.1},{$course.2}</p> {* 显示关联数组 *} <p>名称: {$godBird.name}, 特性: {$godBird.gift}, 绝招: {$godBird.kill}</p> {* 显示多维数据 *} <ul> <li>名称: {$godBirds.0.name}, 特性: {$godBirds.0.gift}, 绝招: {$godBirds.0.kill}</li> <li>名称: {$godBirds.1.name}, 特性: {$godBirds.1.gift}, 绝招: {$godBirds.1.kill}</li> <li>名称: {$godBirds.2.name}, 特性: {$godBirds.2.gift}, 绝招: {$godBirds.2.kill}</li> </ul> {* 显示对象 *} <p>名称: {$test->name}</p> <h3>{$test->welcome()}</h3> {* 自定义函数 *} <p>求和: {add(1,3)}</p> {* 显示常量 *} <p>常量: {$smarty.const.SITE_NAME}</p> {* 显示系统变量 *} <p>POST提交的是:{$smarty.post.user_name}</p> <p>GET提交的是:{$smarty.get.page}</p> <p>SESSION提交的是:{$smarty.session.pass}</p> {* 读取配置文件 *} {config_load file="app.conf"} <h3>应用名称: {$smarty.config.app_name}</h3> <h3>应用名称: {$smarty.config.page_title}</h3>