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

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

  1. 安装
  2. 基础功能实现
  3. mainServerCreate函数注册初始化
  4. 在控制器中使用
  5. 模版渲染文件

理论知识转向官方文档,附链接
https://www.easyswoole.com/Cn...

安装

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

基础类实现

App/Providers/ThinkTpl.php

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




    
    easyswoole think-template


 Hello EasySwoole think-template

你可能感兴趣的:(swoole,easyswoole)