Sian 发表于 2016-1-27 10:26:04

模板引擎Smarty的基本使用

1、使用模板引擎的根本目的是为了让php代码与html代码分离,前端与后台“独立开发”;
2、下载Smarty模板引擎http://www.smarty.net,将lib目录拷贝到项目目录;
3、模拟前端与后台操作,如前端url:http://php.yusian.com   后台url:http://php.yusian.com/Admin;
4、创建模板目录templates并为前端与后台的模板分别建立子目录Home与Admin,模板文件分别在这两个目录下创建;
5、前端php文件为项目根目录下的index.php,后台php文件为Admin目录下的index.php;
6、创建一个全局配置文件init.inc.php;
7、整个目录结构为
----index.php
--index.php
--init.inc.php
------index.html
                  ----index.html
8、部分程序代码:
init.inc.php
<?php
      define(ROOT, dirname(__FILE__));
      include ROOT.'/libs/Smarty.class.php';
      $smarty = new Smarty;
      // 设置模板路径,默认路径为当前php文件所在目录下的templates目录
      $smarty->setTemplateDir(ROOT."/templates");
      // 添加模板路径
//         $smarty->addTemplateDir("./Home");
      // 设置编译文件路径,默认路径为当前php文件所在目录下的templates_c目录
      $smarty->setCompileDir(ROOT."/templates_c");
      // 设置定界符
//         $smarty->setLeftDelimiter("{");index.php<?php
      include 'init.inc.php';
      
      $smarty->assign("content", "Home");
      $smarty->display("Home/index.html");admin.php<?php
      include '../init.inc.php';

      $smarty->assign("content", "admin");
      $smarty->display("Admin/index.html");Home--index.htmlAdmin.index.html----{$content}Admin--index.htmlHome.index.html----{$content}9、效果
http://php.yusian.com
Home.index.html----Homehttp://php.yusian.com/AdminAdmin.index.html----admin
页: [1]
查看完整版本: 模板引擎Smarty的基本使用