通过composer安装
composer require smarty/smarty
php think make:service SmartyService
SmartyService.php
<?php
declare (strict_types=1);
namespace app\service;
class SmartyService extends \think\Service
{
protected $smarty;
/**
* 注册服务
*
* @return mixed
*/
public function register()
{
//初始化Smarty
$this->smarty = new \Smarty();
// 绑定类实例
$this->app->bind(‘smarty‘, $this->smarty);
}
/**
* 执行服务 ,配置Smarty
*
* @return mixed
*/
public function boot()
{
$this->smarty->caching = config(‘smarty.caching‘);
$this->smarty->cache_lifetime = config(‘smarty.cache_lifetime‘);
$this->smarty->setTemplateDir(config(‘smarty.template_dir‘));
$this->smarty->setCompileDir(config(‘smarty.compile_dir‘));
$this->smarty->cache_dir = config(‘smarty.cache_dir‘);
$this->smarty->config_dir = config(‘smarty.config_dir‘);
$this->smarty->setLeftDelimiter(config(‘smarty.left_delimiter‘));
$this->smarty->setRightDelimiter(config(‘smarty.right_delimiter‘));
$this->smarty->auto_literal = config(‘smarty.auto_literal‘);
}
}
在config目录下新建smarty.php
<?php
// +----------------------------------------------------------------------
// | 模板设置
// +----------------------------------------------------------------------
return [
//是否缓存
‘caching‘ => false,
//缓存周期(开启缓存生效)
‘cache_lifetime‘ => 120,
// 设置模板基础路径
‘template_dir‘ => root_path(‘view‘),
// 模板编译路径
‘compile_dir‘ => runtime_path(‘smarty/compile‘),
// 缓存目录
‘cache_dir‘ => runtime_path(‘smarty/cache‘),
// 配置目录(比较鸡肋,建议:使用框架的config就好了)
‘config_dir‘ => config_path(‘smarty‘),
// 模板引擎左边标记
‘left_delimiter‘ => ‘<{‘,
// 模板引擎右边标记
‘right_delimiter‘ => ‘}>‘,
//空格策略
‘auto_literal‘ => false,
];
在控制器中如下
app(‘smarty‘)->display(‘index/index/index.tpl‘, compact(‘articles‘));
可以创建一个BaseController
控制器在构造函数中赋值
//一些公共的数据
app(‘smarty‘)->assign(‘index_info‘, session(‘index_info‘));
这样就能在模板任意地方使用 <{$index_info->nickname}>
原文:https://www.cnblogs.com/lujiahao/p/15219647.html