当前位置: 移动技术网 > IT编程>开发语言>PHP > CodeIgniter集成smarty的方法详解

CodeIgniter集成smarty的方法详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

杨继周,龙游良家,呼和浩特公交线路查询

本文实例讲述了codeigniter集成smarty的方法。分享给大家供大家参考,具体步骤如下:

1.下载smarty

解压到ci的libraries目录 如:

ci/application/libraries/smarty-2.6.20

2.编写mysmarty.php 自己的类库文件

代码如下:

<?php if (!defined('basepath')) exit('no direct script access allowed');
require "smarty-2.6.20/libs/smarty.class.php";
/**
* @file system/application/libraries/mysmarty.php
*/
class mysmarty extends smarty
{
  function mysmarty()
  {
    $this->smarty();
    $config =& get_config();
    // absolute path prevents "template not found" errors
    $this->template_dir = (!empty($config['smarty_template_dir']) ? $config['smarty_template_dir'] : basepath . 'application/views/');
    $this->compile_dir = (!empty($config['smarty_compile_dir']) ? $config['smarty_compile_dir'] : basepath . 'cache/'); 
    //use ci's cache folder
    if (function_exists('site_url')) {
      // url helper required
      $this->assign("site_url", site_url()); // so we can get the full path to ci easily
    }
  }
  /**
  * @param $resource_name string
  * @param $params array holds params that will be passed to the template
  * @desc loads the template
  */
  function view($resource_name, $params = array())  {
    if (strpos($resource_name, '.') === false) {
      $resource_name .= '.html';
    }
    if (is_array($params) && count($params)) {
      foreach ($params as $key => $value) {
        $this->assign($key, $value);
      }
    }
    // check if the template file exists.
    if (!is_file($this->template_dir . $resource_name)) {
      show_error("template: [$resource_name] cannot be found.");
    }
    return parent::display($resource_name);
  }
} // end class smarty_library
?>

3.在autoload.php让ci自动加载smarty

$autoload['libraries'] = array('database', 'mysmarty');

或者 使用模板时再自己加载smarty

$this->load->library("mysmarty");

4.smarty变量赋值 display模板

$this->mysmarty->assign('test', 'hello world.');
$this->mysmarty->view('smarty');

注:images css 等外部资源文件 放在ci系统文件夹外 网站根目录下

最好用:

$this->load->helper('url');

base_url()来访问:

base_url()."images/xxx.jpg"

不要放到system里

补充:小编在这里推荐一款本站的php格式化美化的排版工具帮助大家在以后的php程序设计中进行代码排版:

php代码在线格式化美化工具:

另外,由于php属于c语言风格,因此下面这款工具同样可以实现php代码的格式化:

c语言风格/html/css/json代码格式化美化工具:

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网