Reputation: 80
I know how to set a specific template for the ViewModel. But how would I check if a different template actually exists in the current template path stack before setting the template in the ViewModel? The idea being that I can reuse a single action to render views based on a query parameter. I want to check first so if the view doesn't exists then I can set the response status code to a 404 instead of the generic server error message.
Upvotes: 3
Views: 4552
Reputation: 1
If you're using ZF2Twig it should be:
$template = "non/existant/twig-template";
/** @var \ZfcTwig\View\TwigResolver $resolver */
$resolver = $this->getServiceLocator()->get('ZfcTwig\View\TwigResolver');
if (false === $resolver->resolve($template)) {
// Twig template does not exist
}
Upvotes: 0
Reputation: 291
If you want to check a view exists from another view ( perhaps you are loading a partial ) you can use
<?php if ($this->resolver('layouts/default')) : ?>
<?php $this->render('layouts/default'); ?>
<?php endif; ?>
Test that a view exists in ZF2
Upvotes: 7
Reputation: 12721
you can do the following, assuming you want to do it from a controller
$template = 'non/existant/template';
$resolver = $this->getEvent()
->getApplication()
->getServiceManager()
->get('Zend\View\Resolver\TemplatePathStack');
if (false === $resolver->resolve($template)) {
// does not exist
}
Upvotes: 17