CodeIgniter框架实现的整合Smarty引擎DEMO示例

时间:2022-07-27
本文章向大家介绍CodeIgniter框架实现的整合Smarty引擎DEMO示例,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文实例讲述了CodeIgniter框架实现的整合Smarty引擎。分享给大家供大家参考,具体如下:

Smarty的模板机制很强大,一般情况下CI框架无需整合其他模板标签,因为PHP本身就是一种标签,简单易用。Codeigniter整合Smarty教程(我用的都是最新版本)如下:

第一步:下载Codeigniter最新版本:CodeIgniter框架源码 第二步:下载Smarty最新版本:Smarty引擎源码 第三步:具体配置

我已将本人整合好的代码上传,有兴趣的可以下载阅读。Codeigniter框架整合Smarty引擎DEMO 。

1、准备

将smarty拷贝到application/libraries下,然后再根目录下下新建templates,templates_c,config,cache目录,结构如下:

2、修改入口文件

在入口文件index.php中新增:

define('ROOT', dirname(__FILE__));

3、新建CI_Smarty.php

在libraries文件下新建CI_Smarty.php,写如下代码:

<?php
/**
* =======================================
* Created by PK Technology.
* Author: ZhiHua_W
* Date: 2016/10/31 0031
* Time: 上午 9:16
* Project: CI整合
* Power: CI框架整合smarty
* =======================================
*/
defined('BASEPATH') OR exit('No direct script access allowed');
require(APPPATH . 'libraries/smarty/Smarty.class.php');
class CI_Smarty extends Smarty
{
    public function __construct($template_dir = '', $compile_dir = '', $config_dir = '', $cache_dir = '')
    {
      parent::__construct();
      if (is_array($template_dir)) {
        foreach ($template_dir as $key =  $value) {
          $this- $key = $value;
        }
      } else {
        //ROOT是Codeigniter在入口文件index.php定义的本web应用的根目录
        $this- template_dir = $template_dir ? $template_dir : ROOT . '/templates';
        $this- compile_dir = $compile_dir ? $compile_dir : ROOT . '/templates_c';
        $this- config_dir = $config_dir ? $config_dir : ROOT . '/config';
        $this- cache_dir = $cache_dir ? $cache_dir : ROOT . '/cache';
      }
    }
}

4、在controller中使用

在控制器Welcome.php中写入使用方法,代码如下:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller
{
    /**
     * Welcome constructor.
     * 写入构造函数,引入CI_Smarty类文件
     */
    public function __construct()
    {
      parent::__construct();
      $this- load- library('CI_Smarty');
    }
    /**
     * smarty测试函数
     */
    public function test()
    {
      $this- ci_smarty- assign('test', 'smarty');
      $this- ci_smarty- display('test.tpl');
    }
}

5、创建模版试图

在templates文件夹下创建test.tpl文件,写入如下代码:

<!DOCTYPE html 
<html lang="en" 
<head 
  <meta charset="UTF-8" 
  <title Codeigniter整合Smarty测试</title 
</head 
<body 
这是 {$test} 测试
</body 
</html 

6、访问

至此,我们整合完毕,访问:http://localhost/Codeigniter_Smarty/index.php/Welcome/test即可看到测试结果。

更多关于CodeIgniter相关内容感兴趣的读者可查看本站专题:《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《php优秀开发框架总结》、《ThinkPHP入门教程》、《ThinkPHP常用方法总结》、《Zend FrameWork框架入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于CodeIgniter框架的PHP程序设计有所帮助。