【问题标题】:How to use the partial in zendframework2如何在zend框架2中使用partial
【发布时间】:2015-09-11 15:43:11
【问题描述】:

在 ZF1 中,我们在 layout.phtml 文件中使用类似的部分

$this->partial('header.phtml', array('vr' => 'zf2'));

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

【问题讨论】:

    标签: php zend-framework2 partials view-helpers


    【解决方案1】:

    这可以通过

    来实现
     echo $this->partial('layout/header', array('vr' => 'zf2'));
    

    您可以使用

    访问视图中的变量
    echo $this->vr;
    

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

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

    添加后是这样的

    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',
            ),
    
    
        ),    
    
    );
    

    【讨论】:

    • 将所有视图变量传递给局部:echo $this->partial('layout/header',$this->viewModel()->getCurrent()->getVariables());
    • 请注意,$this->viewModel()->getCurrent()->getVariables() 返回一个 ArrayObject
    • 要合并附加数据,array_merge 有效: echo $this->partial('mypartial', array_merge($this->viewModel()->getCurrent()->getVariables(), [moredata] ));
    【解决方案2】:

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

    echo $this->partial('layout/header', array('vr' => 'zf2'));
    

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


    如果您不想弄乱您的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',
            ),
        ),    
    );
    

    在你的module.config.php 和你的listsn-p.phtml 位于.../view/mycontroller/snippets/listsnippet.phtml,那么你可以使用下面的代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      • 2023-04-06
      • 2014-05-02
      • 2010-09-29
      • 2011-09-13
      相关资源
      最近更新 更多