PHP框架中集成Smarty3模板引擎(二) ------ CakePHP 2.0
来源:程序员人生 发布时间:2014-09-17 12:15:43 阅读次数:4261次
CakePHP 2.0 已经发布,我们尝试一下让他集成smarty 3.0模板引擎。
cakephp版本:2.0.6
smarty版本:3.1.7
步骤如下:
1. 在vendors(和app同级)下新建smarty文件夹,然后把下载下来的smarty包的libs下的文件拷贝进去。
2. 在app/View下新建SmartyView.php,代码如下
App::import('Vendor', 'Smarty', array('file' => 'smarty'.DS.'Smarty.class.php'));
class SmartyView extends View {
function __construct (&$controller) {
parent::__construct($controller);
if (is_object($controller)) {
$count = count($this->__passedVars);
for ($j = 0; $j < $count; $j++) {
$var = $this->__passedVars[$j];
$this->{$var} = $controller->{$var};
}
}
$this->Smarty = new Smarty();
//$this->ext= '.ctp';
$this->Smarty->compile_dir = TMP.'smarty'.DS.'compile'.DS;
$this->Smarty->cache_dir = TMP.'smarty'.DS.'cache'.DS;
$this->Helpers = new HelperCollection($this);
}
protected function _render($___viewFn, $___dataForView = array()) {
if (empty($___dataForView)) {
$___dataForView = $this->viewVars;
}
extract($___dataForView, EXTR_SKIP);
foreach($___dataForView as $data => $value) {
if(!is_object($data)) {
$this->Smarty->assign($data, $value);
}
}
//$this->Smarty->display($___viewFn);
$this->Smarty->assignByRef('this', $this);
return $this->Smarty->fetch($___viewFn);
}
}
3. 在app/View/Layouts下新建default.tpl文件,代码如下:
Layout:
<br />
<br />
{$content_for_layout}
接下来我们可以使用smarty来编写测试代码:
在app/Controller下新建tests_controller.php,代码如下:
class TestsController extends AppController {
var $viewClass = 'Smarty';
//var $autoLayout = false;
function index() {
$name = 'Shen Bin';
$date = date("Y-m-d H:i", time());
$this->set(compact('date', 'name'));
}
}
在app/View/tests下新建index.ctp,代码如下:
{$date}
<hr />
Hello, {$name}!
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠