Zend Framework 2 入门-视图(View)

来源:互联网 发布:burpsuite修改数据 编辑:程序博客网 时间:2024/05/20 14:44

1、调用自定义视图

在默认情况下控制器中的action和view是一一对应的,比如HellowordController::indexAction()(path:  /module/Application/src/Application/Controller/HellowordController.php)对应的视图文件为index.phtml(path: /module/Application/view/application/helloword/index.phtml)。

在ZF2中也可以自定义视图:

首先建立自己的自定义视图文件my.phtml(当然非必须是phtml文件)

(path://module/Application/view/application/myviews/my.phtml)

然后直接在控制器中调用:

 <?phpnamespace Application\Controller;use Zend\Mvc\Controller\AbstractActionController;use Zend\View\Model\ViewModel;class HellowordController exntends AbstractActionController{    public function indexAction()    {        $view = new ViewModel();        $view->setTemplate('application/myviews/my.phtml');        return $view;    }}

也可以参考默认的’error/404′方式,在module.config.php文件中添加你的”view_manager”配置信息

<?phpreturn array(    ...   'view_manager' => array(       'template_path_stack' => array(           __DIR__ . '/../view',       ),       'template_map' => array(            'myviews/my' => __DIR__ . '/../view/application/myviews/my.phtml',        ),    ),    ...

然后就可以在视图中实际使用“myviews/my”

$view = new ViewModel();$view->setTemplate('myviews/my');return $view;

2、指定layout

方法与上面比较类似,首先在module.config.php配置layout参数

return array(    'view_manager' => array( 'template_map' => array(     'myviews/layout'   => __DIR__ . '/../view/layout/layout.phtml', ),        'template_path_stack' => array(            __DIR__ . '/../view',        ),    ),);
注意:建议module.config.php文件要与view模块一一对应,因为view_manager中采用的相对路劲,一一对应的方式便于操作

然后就可以在控制器中配饰当前layout

public function indexAction(){    $this->layout('myviews/layout');}

3、不使用layout直接调用对应的视图

public function indexAction(){    $view  = new ViewModel();    $view->setTerminal(true);     //设置不使用layout    $view->setVariables(array()); //向view中传参    return $view;}

4、在view中向layout中传递参数

例如在index.phtml中向layout.phtml传参

index.phtml :

$this->layout()->helloword = 'Hi';

layout.phtml:

echo $this->layout()->helloword; //output: Hi

5、不使用views直接打印出参数

IndexController.php

public function indexAction(){     return $this->getResponse()                 ->setStatusCode(200)                 ->setContent('foo');}//optput foo

6、在action中直接向layout传递参数

Module.php:

class Module{    ...    public function onBootstrap( $e )    {$eventManager = $e->getApplication()->getEventManager();$eventManager->attach( \Zend\Mvc\MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 100 );    }     public function preDispatch($e)     {    ...    $e->getViewModel()->setVariable('names', 'start');        ...    }    ...}

layout.phtml:

echo $this->layout()->names;//output start
0 0