Since ZF 2.4.0 was realized the new resolver Zend\View\Resolver\PrefixPathStackResolver
with prefix_template_path_stack
config key had been added.
This resolver allows creating namespace
or prefix
for your templates.
For example, you create a universal module which can work in ZF3 and ZF Expressive. You give names to your templates such as user::login
, user::logout
or admin::dashboard
etc.
At first glance, you can add all maps to template_map
of view_manager
config and this will work great. But we are lazy and don’t want to write down all templates in config. Moreover, we can add new templates in the future and they also need to be declared in template_map
.
In this case, we can use more right aproach. We need add new config key prefix_template_path_stack
and declare named path to our templates.
// path/to/Your/Module/config/module.config.php
return [
// ...
'view_manager' => [
'template_map' => [
// ...
],
'template_path_stack' => [
// ...
],
'prefix_template_path_stack' => [
'user::' => __DIR__ . '/../view',
],
],
];
Notice! You can you any delimeter in prefix. Example above uses ::
but this can be any other symbols.
Now, you can add named template to your ViewModel
in your action or middleware
class LoginAction
{
// ...
public function __invoke($request, $response)
{
$viewModel = new ViewModel();
$viewModel->setTemplate('user::login');
// ...
}
// ...
}
ViewRendere
will automatically resolve your named template to path/to/Your/Module/view/login.phtml
and render it.
If your named template will have the name user::widget/stats
, this will be resolved to path/to/Your/Module/view/widget/stats.phtml
and so on.