五步走,在easyswoole中使用think-template模板引擎
- 安装
- 基础功能实现
- mainServerCreate函数注册初始化
- 在控制器中使用
- 模版渲染文件
理论知识转向官方文档,附链接
https://www.easyswoole.com/Cn...
安装
composer require easyswoole/template
composer require topthink/think-template
基础类实现
App/Providers/ThinkTpl.php
<?php
namespace App\Providers;
use EasySwoole\Template\RenderInterface;
class ThinkTpl implements RenderInterface
{
protected $template;
public function __construct()
{
$this->template = new \think\Template([
'view_path' => EASYSWOOLE_ROOT.'/App/Views/',
'cache_path' => EASYSWOOLE_ROOT.'/Temp/runtime/',
]);
}
public function render(string $template, array $data = [], array $options = []): ?string
{
// TODO: Implement render() method.
ob_start();
$this->template->assign($data);
$this->template->fetch($template);
$content = ob_get_contents() ;
return $content;
}
public function afterRender(?string $result, string $template, array $data = [], array $options = [])
{
// TODO: Implement afterRender() method.
}
public function onException(\Throwable $throwable): string
{
// TODO: Implement onException() method.
$msg = "{$throwable->getMessage()} at file:{$throwable->getFile()} line:{$throwable->getLine()}";
trigger_error($msg);
return $msg;
}
}
mainServerCreate函数注册初始化
use EasySwoole\Template\Render;
use App\Providers\ThinkTpl;
$render = Render::getInstance();
$render->getConfig()->setRender(new ThinkTpl());
$render->attachServer(ServerManager::getInstance()->getSwooleServer());
控制器使用
// 该方法放在控制器基类中,为以后提供方便
public function fetch($tpl='', $data=[]){
if($tpl == ''){
$tpl = $this->getActionName();
}
$this->response()->write(Render::getInstance()->render($tpl,$data));
}
//在某个控制器中的index方法
public function index()
{
return $this->fetch();
}
页面渲染App/Views/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>easyswoole think-template</title>
</head>
<body>
Hello EasySwoole think-template
</body>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。