我必须硬编码才能添加新布局。然后我想找到一些方法在 ZF2 中添加模板映射动态。
我的 module.config.php
'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__ . '/../../../template/layout/layout.phtml',
'layout/custom' => __DIR__ . '/../../../template/layout/custom.phtml',
'error/404' => __DIR__ . '/../../../template/error/404.phtml',
'error/index' => __DIR__ . '/../../../template/error/index.phtml'
),
'template_path_stack' => array (
__DIR__ . '/../view/'
)
)
我通过这种方式设置了新的布局
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$controller->layout('template_name');
}, 100);
请给我一些建议/样品
谢谢 !
===================
2012 年 12 月 8 日更新:
我找到了解决方案并应用于我的“层次模板系统”
修改module.config.php
'template_path_stack' => array (
__DIR__ . '/../view/',
__DIR__ . '/../../../' //Parent folder of template path
)
在 Module.php 中添加:
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$controllerClass = get_class($controller);
//Get routing info
$controllerArr = explode('\\', $controllerClass);
$currentRoute = array(
'module' => strtolower($controllerArr[0]),
'controller' => strtolower(str_replace("Controller", "", $controllerArr[2])),
'action' => strtolower($controller->getEvent()->getRouteMatch()->getParam('action'))
);
//Get curr route
$currAction = implode('/',$currentRoute);
$currController = $currentRoute['module'] . '/' . $currentRoute['controller'];
$currModule = $currentRoute['module'];
//Template file location
$templatePath = __DIR__ .'/../../template/';
//Set template
$template = 'layout/layout'; // Default template
if (file_exists($templatePath . $currAction.'.phtml')) {
$template = $currAction;
}else if(file_exists($templatePath . $currController.'.phtml')) {
$template = $currController;
}else if(file_exists($templatePath . $currModule.'.phtml')) {
$template = $currModule;
}else{
if($currentRoute['controller']=='admin'){
$template = 'admin/layout'; // Admin default template
}
}
$controller->layout('template/'.$template); //Pevert duplicate layout
}, 100);
注意:如果您在“布局”和“视图”之间设置相同的关键变量。它将呈现重复的“布局”并且不理解您当前的视图