它不起作用,因为您无权访问部分中的视图变量。您可以访问传递给部分的数据。
$out = $this->view->partialLoop('tab/partial.phtml', $data);
这行代码可以访问$data
.
因此,您当前部分中的这段代码基本上没有意义:
$v = $this->partialLoop()->view; //you choose to assign view data to the partial, and I don't think it's working as expected.
//By not passing any args to the partial you have at least some access to the view object.
$this->view->test = "This works";//assign data to view locally
echo $v->test; // you seem to be echoing out locally assigned data
$v->myArray[] = "hello";//you didn't assign this to the view
echo count($v->myArray); // myArray probably doesn't exist in this context or dosen't work as expected. If you make this an associative array it might work.
我认为我以前从未见过以这种方式使用的部分。部分的要点是为视图的特定部分建立不同的变量范围。
partial 和 partialLoop 是视图助手,因此您需要在控制器中执行的唯一操作(数据可能来自或来自模型)是提供您想要在局部中使用的任何数据以及您想要的任何数据在您的正常视图范围内可用。
//in a controller
public function userAction() {
$model = Application_Model_DbTable_User();//Table columns = id, name, role
$this->view->partailData = $model->fetchAll();//assign data to view that we want to use in partial, should be an array or object.
}
//in a view script
<?php
//pass the path to the partial as the first arg and the data to be displayed as the second arg
echo $this->partialLoop('/path/to/partial.phtml', $this->partialData);
//we could pass data explicitly as well
echo $this->partial('/path/to/partial.phtml', array('id'=>1,'name'=>'jason','role'=>'user'));
?>
//now for our partial.phtml
//this could be used a simple partial or as a partialLoop
<p>My name is <?php echo $this->name ?>.</p>
<p>My data file id is <?php echo $this->id ?>.</p>
<p>My access control role is <?php echo $this->role ?>. </p>
<!-- name, id and role would be column names that we retrieved from the database and assigned to the view -->
要使用 partial 或 partialLoop,您需要传递某种类型的数组或实现 toArray() 的对象。
[编辑]
清理您仍然在左侧字段中的代码。
//controller code
$this->view->myArray = array();
//view code
<?php $v = $this->partial()->view ?>
<?php $v->myArray[] = 'newName' ?>
<?php Zend_Debug::dump(count($this->partial()->view->myArray)) ?>
//my output =
int(1)
如果我分配给实际的部分脚本并尝试输出视图对象,则会引发错误,我似乎无法进一步传递视图:
//my view again
<?php echo $this->partial('partial.phtml', $this->partial()->view) ?>
//This and attempts similar result in the error
/*Catchable fatal error: Object of class Zend_View could not be converted to string in E:\www\home-local\application\views\scripts\partial.phtml on line 1*/
//when the partial.phtml looks like
<?php echo $this />
//however when I access the data available in the view
<?php echo $this->myArray[0] ?>
//the result works and the output is
newName
当您已经可以访问视图对象时,它看起来像一个空的 partial() (partialLoop()) 调用将让您访问视图对象。如果您离开视图对象的范围,您将只能访问由 __get() 和 __call() 提供的当前范围。
我希望我能够解释这一点足以提供帮助。