如何在Zend Expressive中渲染之前检查模板的存在?

时间:2016-05-08 13:13:10

标签: php zend-expressive

如何在Zend Expressive中渲染之前检查模板?这是我的行动:

class Section
{
    private $container;
    private $template;

    public function __construct(ContainerInterface $container, Template\TemplateRendererInterface $template = null)
    {
        $this->container = $container;
        $this->template  = $template;
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {
        if (false === 'Exist or Not') {
            return $next($request, $response->withStatus(404), 'Not found');
        }

        return new HtmlResponse($this->template->render('app::'.$request->getAttribute('path')));
    }
}

我是ZE的新人。不知道如何做到这一点。

1 个答案:

答案 0 :(得分:1)

据我所知,无法检查模板是否存在。如果找不到模板,则会抛出异常。

使用它的预期方法是为每个操作创建一个模板。

class PostIndexAction
{
    private $container;
    private $template;

    public function __construct(ContainerInterface $container, Template\TemplateRendererInterface $template = null)
    {
        $this->container = $container;
        $this->template  = $template;
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {
        return new HtmlResponse($this->template->render('app::post-index'));
    }
}

第二幕:

class PostViewAction
{
    private $container;
    private $template;

    public function __construct(ContainerInterface $container, Template\TemplateRendererInterface $template = null)
    {
        $this->container = $container;
        $this->template  = $template;
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {
        return new HtmlResponse($this->template->render('app::post-view'));
    }
}