php框架smarty,php框架ci配置smarty详细教程笔记

需要用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里面都存在.

$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的文件.这里主要是加载配置文件等.

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_smarty

$autoload[‘libraries’] = array(‘ci_smarty’);

自定义控制器

在core文件夹添加一个My_Controller.php的自定义控制器.将smarty的assign和display两个函数添加进入.

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就可以使用这两个函数了.

实例

控制器继承需要修改为My_Controller

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文件

{$data.title}

{$data.num}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值