yii2-smarty这个扩展提供了一个ViewRender允许你在 Yii 框架 2.0 中使用Smarty视图模板引擎。
// 本文基于yii2-app-basic安装,如已安装yii请看下一步:
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
安装
进入yii目录,安装Smarty扩展的首选方法是通过composer。
// 运行composer:
composer require --prefer-dist yiisoft/yii2-smarty
或添加
// composer.json 中增加 require 部分
"yiisoft/yii2-smarty": "~2.0.0"
用法
要使用此扩展,只需在应用程序配置中添加以下代码:
return [
//....
'components' => [
'view' => [
'renderers' => [
'tpl' => [
'class' => 'yii\smarty\ViewRenderer' ,
//'cachePath' => '@runtime/Smarty/cache',
],
],
],
],
];
测试
这里我们尝试用smarty写一个about页面类似的about2页面,
1、打开控制器controllers/SiteController.php文件:
查找:
/**
* Displays about page.
*
* @return string
*/
public function actionAbout()
{
return $this->render('about');
}
下面加:
/**
* Displays about2 page.
*
* @return string
*/
public function actionAbout2()
{
$data = [
'title' => 'About Test, Say: "Hello world!',
'content' => 'This is the About page. You may modify the following file to customize its content:',
];
return $this->render('about.tpl', $data);
}
2、新建视图模板views/site/about.tpl文件:
smarty的模板内容如下:
{use class="yii\helpers\Html"}
<div class="site-about">
<h1>{Html::encode($title)}</h1>
<p>
{$content|escape}
</p>
<code><?= __FILE__ ?></code>
</div>
对比php原生的模板内容如下:
<?php
/* @var $this yii\web\View */
use yii\helpers\Html;
$this->title = 'About';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-about">
<h1><?= Html::encode($this->title) ?></h1>
<p>
This is the About page. You may modify the following file to customize its content:
</p>
<code><?= __FILE__ ?></code>
</div>
总结:yii2-smarty模板中不支持php代码,{php}标签无法运行,__FILE__ 调用失败留下了遗憾。
官方文档:https://github.com/yiisoft/yii2-smarty/blob/HEAD/docs/guide/README.md
转载请注明出处:https://www.onexin.net/yii-2-0-smarty/