簡體   English   中英

如何在zf2中從Module.php發送數據以進行查看

[英]How to send data to view from Module.php in zf2

我搜索了相同的內容,並得到了一些答案,但沒有幫助。

我嘗試過的方法如下:

1)

在onBootstrap($ e)函數中:

$e->getViewModel()->setVariable('test_variable', 'Hello World!');
        //or
$e->getViewModel()->test_variable = 'Hello World!';

2)我在Module.php中創建了一個函數

function boforeDispatch(MvcEvent $event) {
    $event->getViewModel()->setVariable('test_variable', 'Hello World!');
    //or
    $event->getViewModel()->test_variable = 'Hello World!';
}

並在onBootstrap($ e)函數中調用了此函數

$application = $e->getApplication();
$eventManager = $application->getEventManager();
$eventManager->attach(MvcEvent::EVENT_DISPATCH, array($this, 'boforeDispatch'), 100);

當我嘗試着看

echo $test_variable;

undefined variable test_variable in ...undefined variable test_variable in ...錯誤。

任何想法?

嘗試使用渲染事件( MvcEvent::EVENT_RENDER )代替:

public function onBootstrap($event){
    $application = $event->getApplication();
    $eventManager = $application->getEventManager();
    $events->attach(MvcEvent::EVENT_RENDER, array($this, 'addVariablesToViewModel'), 100);
}

public function addVariablesToViewModel($event)
{
    $viewModel = $this->getEvent()->getViewModel();
    $viewModel->setVariables(array(
        'key' => 'value',
    ));
}

您的視圖模型可能尚未在(預)調度中使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM