首先复制一份smarty源文件到application/libraries目录下。 自定义smarty配置文件方便修改:config/cismarty.php
// The name of the directory where templates are located.
$config['template_dir'] = APPPATH . 'views/';
// The directory where compiled templates are located
//注意这里要手动建立文件
$config['compile_dir'] = APPPATH . 'cache/compile/';
//This tells Smarty whether or not to cache the output of the templates to the $cache_dir.
$config['caching'] = 0;
// This forces Smarty to (re)compile templates on every invocation. When deploying, change this value to 0
$config['force_compile'] = 1;
$config['compile_check'] = TRUE;
// The delimiter for smarty
$config['left_delimiter'] = '{%';
$config['right_delimiter'] = '%}';
以上都是smarty一些常量 然后创建类 application/libraries/CI_smarty.php
<?php
require_once(APPPATH.'libraries/smarty/Smarty.class.php');
class CI_smarty extends Smarty{
private $config;
function CI_smarty(){
parent::Smarty();
require_once(APPPATH.'config/cismarty.php');
$this->config = $config;//$config 是cismarty.php中数组变量名
if(count($this->config)>0)
{
$this->initialize($this->config);
}
}
/**
* Initialize preferences
*/
function initialize($config = array()) {
foreach ($config as $key => $val) {
if (isset($this->$key)) {
//这里是根据自己需要扩展一些set方法
$method = 'set_'.$key;
if (method_exists($this, $method)) {
$this->$method($val);
} else {
//修改smarty源文件默认变量,这里是自定义cismarty数组值
$this->$key = $val;
}
}
}
}
}
?>
然后在application/config/autoload.php 找$autoload[’libraries’] = array(’CI_smarty’); CI_smarty对应上面类。
测试: 控制器中使用
$val = 'This is ci_smarty test';
$this->ci_smarty->assign_by_ref('val',$val);
$this->ci_smarty->display('test.html');
到顶部