首页 php

Easyswoole中实现think-template模板引擎使用

发布于: 2020-06-23

五步走,在easyswoole中使用think-template模板引擎

  1. 安装

  2. 基础功能实现

  3. mainServerCreate函数注册初始化

  4. 在控制器中使用

  5. 模版渲染文件

详细语言描述看官网:https://www.easyswoole.com/Cn/Components/template.html

安装

1
2
composer require easyswoole/template
composer require topthink/think-template

基础类实现

App/Providers/ThinkTpl.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?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函数注册初始化

1
2
3
4
5
6
use EasySwoole\Template\Render;
use App\Providers\ThinkTpl;

$render = Render::getInstance();
$render->getConfig()->setRender(new ThinkTpl());
$render->attachServer(ServerManager::getInstance()->getSwooleServer());

控制器使用

1
2
3
4
5
6
7
8
9
10
11
12
13
// 该方法放在控制器基类中,为以后提供方便
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

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>easyswoole think-template</title>
</head>
<body>
Hello EasySwoole think-template
</body>
</html>