CodeIgniter集成Smarty模板引擎的详细步骤
本实例分享了将Smarty模板引擎整合到CodeIgniter框架中的具体方案,供读者参考学习,主要包含以下操作细节:
第一步是获取Smarty组件
将解压后的Smarty文件放置于CodeIgniter的libraries目录下,例如:
ci/application/libraries/Smarty-2.6.20
第二步是创建名为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
?>
第三步配置autoload.php以实现CodeIgniter对Smarty的自动加载
$autoload['libraries'] = array('database', 'mysmarty');
或者选择在需要使用时通过代码手动加载Smarty库
$this->load->library("mysmarty");
第四步进行Smarty变量的赋值及模板页面的展示
$this->mysmarty->assign('test', 'Hello World.');
$this->mysmarty->view('smarty');
注意:images、css等静态资源文件应放置在CodeIgniter系统文件夹之外,即网站根目录下
推荐采用以下方式引用资源:
$this->load->helper('url');
使用base_url()函数构建路径:
base_url()."images/xxx.jpg"
避免将资源文件放入system目录中
补充推荐一款本站提供的PHP代码格式化美化工具,有助于后续PHP程序设计的代码排版工作:
php代码在线格式化美化工具:
此外,鉴于PHP语法风格类似C语言,以下工具同样适用于PHP代码的格式化:
C语言风格/HTML/CSS/json代码格式化美化工具: 点击使用
希望上述内容能对基于CodeIgniter框架进行PHP程序设计的人员提供有益帮助。