如何在zendframework2中使用partial

Dev*_*per 5 php partials view-helpers zend-framework2

在ZF1中,我们在layout.phtml文件中使用partial

$this->partial('header.phtml', array('vr' => 'zf2'));
Run Code Online (Sandbox Code Playgroud)

我们如何在ZF2中做同样的事情?

Dev*_*per 27

这可以通过实现

 echo $this->partial('layout/header', array('vr' => 'zf2'));
Run Code Online (Sandbox Code Playgroud)

您可以使用查看视图中的变量

echo $this->vr;
Run Code Online (Sandbox Code Playgroud)

不要忘记在module.config.php文件的view_manager中添加以下行.

'layout/header'           => __DIR__ . '/../view/layout/header.phtml',  
Run Code Online (Sandbox Code Playgroud)

添加后它看起来像这样

return array(  

'view_manager' => array(
        'template_path_stack' => array(
            'user' => __DIR__ . '/../view' ,
        ),
        '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',

            'layout/header'           => __DIR__ . '/../view/layout/header.phtml',            

            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ),


    ),    

);
Run Code Online (Sandbox Code Playgroud)

  • 将所有视图变量传递给部分:`echo $this->partial('layout/header',$this->viewModel()->getCurrent()->getVariables());` (2认同)

小智 6

正如已接受的答案中所述,您可以使用

echo $this->partial('layout/header', array('vr' => 'zf2'));
Run Code Online (Sandbox Code Playgroud)

但是你必须layout/header在你的module.config.php中定义.


如果你不想弄乱你的template_map,你可以使用基于的相对路径template_path_stack直接指向你的部分.

假设你定义了:

'view_manager' => array(
        /* [...] */
        'template_path_stack' => array(
            'user' => __DIR__ . '/../view' ,
        ),
        'template_map' => array(
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',

            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ),
    ),    
);
Run Code Online (Sandbox Code Playgroud)

在您的module.config.php和您的listsnippet.phtml中.../view/mycontroller/snippets/listsnippet.phtml,您可以使用以下代码:

echo $this->partial('mycontroller/snippets/listsnippet.phtml', array('key' => 'value'));
Run Code Online (Sandbox Code Playgroud)