0

How to check template before rendering in Zend Expressive? Here is my action:

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')));
    }
}

I am new in ZE. Have no Idea how to do this.

edigu
  • 9,878
  • 5
  • 57
  • 80
Philipp Klemeshov
  • 383
  • 1
  • 5
  • 14

1 Answers1

1

As far as I know there is no way to check if a template exists. If a template is not found, it throws an exception.

The intended way to use it is by creating a template for each action.

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'));
    }
}

2nd action:

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'));
    }
}
xtreamwayz
  • 1,285
  • 8
  • 10