需要用ci来写一个后台配置smarty,在网络上能够找到一些相关的文章.但是都是比较旧的内容,大部分是smary2.*
的配置方法.按照这个配置后会出现一些错误.其实配置看smary官方会比较简单.
基础
在php中使用smarty的用法
require_once('Smarty.class.php');$smarty = new Smarty();
这里就可以使用对象$smarty
的assign和display对象来解析模板.在ci里面使用时为了在controller里面来使用这两个函数.
配置
smarty里面有4个需要配置的项
$smarty->setTemplateDir( ...);$smarty->setCompileDir(... );$smarty->setConfigDir( ...);$smarty->setCacheDir(... );
那么我们在ci的config里面创建一个smarty.php的文件,并加入4个变量.其中APPPATH
的值为application目录.创建'templates_c',其他三个文件夹ci里面都存在.
类库
首先将smarty的lib目录复制到ci的libraries目录,并改名为smarty.在libraries里面创建一个ci_smarty.php
的文件.这里主要是加载配置文件等.
ci = & get_instance(); $this->ci->load->config('smarty');//加载smarty的配置文件 //获取相关的配置项 // $this->template_dir= .. ;这是2.*的方法,3.1之后修改为 getXXX setXXX $this->setTemplateDir($this->ci->config->item('template_dir')); $this->setCompileDir($this->ci->config->item('compile_dir')); $this->setCacheDir($this->ci->config->item('cache_dir')); $this->setConfigDir($this->ci->config->item('config_dir')); } }
然后在config/autoload.php里面设置自动加载Ci_smarty
$autoload['libraries'] = array('ci_smarty');
自定义控制器
在core
文件夹添加一个My_Controller.php
的自定义控制器.将smarty的assign和display两个函数添加进入.
ci_smarty->assign($key,$val); } public function display($html) { $this->ci_smarty->display($html); } }
将控制器继承自My_Controller就可以使用这两个函数了.
实例
控制器继承需要修改为My_Controller
load->view('welcome_message'); $data["title"]="标题"; $data["num"]="123123"; $this->assign('data',$data); $this->display("index.html"); }}
view文件夹中的index.html文件
{$data.title} {$data.num}