温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在CodeIgniter框架中使用Smarty引擎

发布时间:2021-05-27 16:40:25 来源:亿速云 阅读:125 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关如何在CodeIgniter框架中使用Smarty引擎,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

1、准备

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

如何在CodeIgniter框架中使用Smarty引擎

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>

看完上述内容,你们对如何在CodeIgniter框架中使用Smarty引擎有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI