须要用ci来写一个后台配置smarty,在网络上可以找到一些相关的文章.可是都是比较旧的内容,大部分是smary2.*
的配置方法.按照这个配置后会出现一些错误.其实配置看smary官方会比较简单.php
在php中使用smarty的用法html
require_once('Smarty.class.php'); $smarty = new Smarty();
这里就能够使用对象$smarty
的assign和display对象来解析模板.在ci里面使用时为了在controller里面来使用这两个函数.网络
smarty里面有4个须要配置的项app
$smarty->setTemplateDir( ...); $smarty->setCompileDir(... ); $smarty->setConfigDir( ...); $smarty->setCacheDir(... );
那么咱们在ci的config里面建立一个smarty.php的文件,并加入4个变量.其中APPPATH
的值为application目录.建立'templates_c',其余三个文件夹ci里面都存在.函数
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); $config['template_dir'] = APPPATH . 'views'; $config['compile_dir'] = APPPATH . 'templates_c'; $config['cache_dir'] = APPPATH . 'cache'; $config['config_dir'] = APPPATH . 'config';
首先将smarty的lib目录复制到ci的libraries目录,并更名为smarty.在libraries里面建立一个ci_smarty.php
的文件.这里主要是加载配置文件等.ui
<?php if(!defined('BASEPATH')) EXIT('No direct script asscess allowed'); require_once( APPPATH . 'libraries/smarty/Smarty.class.php' ); class Ci_smarty extends Smarty { protected $ci; public function __construct(){ parent::__construct(); $this->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_smartythis
$autoload['libraries'] = array('ci_smarty');
在core
文件夹添加一个My_Controller.php
的自定义控制器.将smarty的assign和display两个函数添加进入.code
<?php if(!defined('BASEPATH')) EXIT('No direct script asscess allowed'); class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); } public function assign($key,$val) { $this->ci_smarty->assign($key,$val); } public function display($html) { $this->ci_smarty->display($html); } }
将控制器继承自My_Controller就能够使用这两个函数了.htm
控制器继承须要修改成My_Controller对象
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Welcome extends My_Controller { public function index() { //$this->load->view('welcome_message'); $data["title"]="标题"; $data["num"]="123123"; $this->assign('data',$data); $this->display("index.html"); } }
view文件夹中的index.html文件
<html> <head> <title>{$data.title}</title> </head> <body> <p>{$data.num}</p> </body> </html>