I'm trying to load a different view depending on the value taken from a Regex route, but I can't get the ViewModel to load the template
public function viewAction()
{
$page = $this->params()->fromRoute()["page"];
$view = new ViewModel();
$view->setTemplate('module/Base/view/base/index/$page');
return $view;
}
I'm following the conventional module setup:
Base
|- config
| |- module.config.php
|- src
| |- Base
| |- Controller
| |- IndexController.php
|- view
|- base
| |- index
| |- index.phtml
| |- other.phtml
|- layout
And my view_manager configuration is:
'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
I've tried all sort of values in the path passed to setTemplate, but I just keep getting the application error message, but no error log or details (that may be because I haven't figured out displaying errors properly). I have confirmed that $page
is getting the name of the template correctly from the URL, and the template is in the correct directory.
So, where does ViewModel start looking for templates?
I've tried:
$view->setTemplate('$page.phtml');
$view->setTemplate('$page');
$view->setTemplate('base/index/$page.phtml');
$view->setTemplate('base/index/$page');
$view->setTemplate('module/Base/view/base/index/$page.phtml');
$view->setTemplate('module/Base/view/base/index/$page');
Each module that requires view scripts should have a view_manager
key in module.config.php
You have two choices when registering view scripts.
'view_manager' => [
'template_map' => [
'module-name/foo/bar' => __DIR__ . '/../view/foo/bar.phtml',
'custom_view_template_name' => __DIR__ . '/../view/some/other/path/bar.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
Template Path Stack
This represents a collection (stack) of paths that the view resolver will try to find paths from.
The view scripts that you set on the view models in the controller would then be relative to this directory path. This option saves you time by 'automatically' resolving view script paths using a common naming convention.
For example, if you have FooModule
and the file FooModule/view/foo-module/index/index.phtml
the template path that should be used in the controller would be foo-module/index/index
.
Template Map
A one to one mapping of template name to template path. This means the template path is exactly the same as the array key.
You should try to favor this method as using the template_path_stack
incurs a slight performance hit as the view scripts need to be resolved at runtime.