构建Smarty类库
一、构建Smarty类库
第一步,把Smarty的libs目录拷贝至CodeIgniter的libraries文件夹内,建议将其重命名为smarty以便管理。 第二步,建立名为Cismarty.php的新文件。注意文件名与类名首字母需大写以符合规范,但在控制器中调用加载时,类名及文件名无需保持大写格式。
Cismarty.php
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
require(APPPATH . 'libraries/smarty/Smarty.class.php');
//CI,文件系统全用相对路径相对index.php所在的路径,url全部用绝对路径。
//BASEPATH - The full server path to the "system" folder
//APPPATH - The full server path to the "application" folder
class Cismarty extends Smarty
{
public function __construct()
{
parent::__construct();
$this->caching = false;
$this->setTemplateDir(APPPATH . 'views/Smarty/templates'); //设定所有模板文件都需要放置的目录地址。
$this->setConfigDir(APPPATH . 'views/Smarty/configs'); //设定用于存放模板特殊配置文件的目录,
$this->setCacheDir(APPPATH . 'views/Smarty/cache'); //在启动缓存特性的情况下,这个属性所指定的目录中放置Smarty缓存的所有模板
$this->setPluginsDir(APPPATH . 'views/Smarty/plugins'); //插件目录
$this->setCompileDir(APPPATH . 'views/Smarty/templates_c'); //设定Smarty编译过的所有模板文件的存放目录地址
}
}
?>
在指定目录下创建Smarty所需的子文件夹,包括templates(模板)、configs(配置)、cache(缓存)、plugins(插件)以及templates_c(编译模板)。
二、编写控制器文件
创建控制器文件paper.php,确保类名首字母大写。当通过load方法加载libraries时,系统默认执行构造器函数;若通过URL路由直接访问控制器,则会依次执行构造器函数及默认的index方法。 paper.php:
<?php
class Paper extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function pri_body()
{
$this->load->library('cismarty');
$this->cismarty->assign("name", 1200);
$this->cismarty->display('dd.tpl');
}
}
?>
此外,也可以在application/config/autoload.php配置文件中进行设置,以实现资源的自动加载。