返回首页 - Notes - 2014

CodeIgniter 集成 Smarty


集成Smarty模版引擎

下载 Smarty 类库,将其放置到 application/libraries/libs 路径

application/libraries 目录下新建文件 MySmarty.php,内容如下:

<?php

include_once __DIR__.'/libs/Smarty.class.php';


class MySmarty extends Smarty {

    public function __construct () {
        parent::__construct();

        $this->template_dir    = __DIR__.'/../views/templates';
        $this->compile_dir     = __DIR__.'/../views/templates_c';
        $this->left_delimiter  = '<{';
        $this->right_delimiter = '}>';
    }

}

修改默认控制器开启性能分析

application/core 目录下新建文件 MY_Controller.php,内容如下:

<?php

class MY_Controller extends CI_Controller {

    public function __construct () {
        parent::__construct();

        $this->load->library('MySmarty');
        $this->smarty = new MySmarty;

        if (ENVIRONMENT == 'development') {
            $this->output->enable_profiler(true);
        }
    }

}

.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>

使用方法

application/views 下创建两文件夹:templatestemplates_c

application/controllers 目录下新建控制器文件 hello.php,内容如下:

<?php

class Hello extends MY_Controller {

    public function index ($name = 'Ruchee') {
        $data['title'] = "Hello {$name}";
        $data['content'] = "{$name},欢迎你的来访";

        $this->smarty->assign($data);
        $this->smarty->display('hello.tpl');
    }

}

application/views/templates 目录下新建视图文件 hello.tpl,内容如下:

<!DOCTYPE HTML>
<html>
    <head>
        <title><{$title}></title>
    </head>
    <body>
        <h1><{$content}></h1>
    </body>
</html>

打开浏览器,访问 http://你本地项目路径/hello/index/PHPer,你就会看到标题为 Hello PHPer 的页面了


date : 2014-02-17、2014-02-18