Test that a view exists in Zend Framework 2

Posted in August 2012 by under zend-framework

When you need to include a page specific layout or some other file in your View, you render the other file using

<?php $this->render('layouts/default'); ?>

The PhpRenderer will attempt to load the file based on your configuration. In this case, it is likely be looking for the file view/layouts/default.phtml

If you attempt to render that file and that file does not exist, then PhpRenderer will raise a fatal error and you will see the following message :

Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'Zend\View\Renderer\PhpRenderer::render: Unable to render template "layouts/default"; resolver could not resolve to a file' in .../vendor/zendframework/zendframework/library/Zend/View/Renderer/PhpRenderer.php:451.

This usually is not a problem as you know which files exist when you create the view. However, if you need to, you can test that the PhpRenderer can resolve the file before attempting to render it. The code will then look like

<?php if ($this->resolver('layouts/default')) : ?>
    <?php $this->render('layouts/default'); ?>
<?php endif; ?>

If the resolver() function can resolve the location of the file, it will return the full path of the file to be rendered. If it cannot find the file, the function will return false.