// in view script
<?php
$this->showLogo = true;
$this->render('header.phtml');
// in header.phtml
<?php if ($this->showLogo): ?>
<img ... />
<?php endif; ?>
However, I would suggest using Zend_Layout instead -- it's much better at handling layout-specific tasks and it contains it's own view instance, allowing you to set view vars like this:
// in view script
<?php
$this->layout()->showLogo = true;
// in layout
<?php if ($this->layout()->showLogo): ?>
<img ... />
<?php endif; ?>
--
Hector
On Mon, Feb 22, 2010 at 4:14 PM, electrotype <electrotype@gmail.com> wrote:
I want to be able to pass some parameters to a template I include. For
example, in a template I would like to include another template,
'header.phtml', and telling it to show a logo or not:
----------------------
<div id="top">
<?php
// doesn't work: no parameters allowed
$header = $this->render('header.phtml', array('showLogo' => true));
echo $header;
?>
</div>
<div>
some other content
</div>
----------------------
The default Zend_View doesn't allow that. I think it's not possible to do
that with placeholders either. So I coded my own solution, but I want to be
sure there is not an already existing solution I didn't see!
My solution:
-----------------
// I use my own view class
class My_View extends Zend_View
{
protected $_renderParameters = array();
protected function setRenderParameters($renderParameters)
{
$this->_renderParameters = $renderParameters;
}
protected function addRenderParameters($parameters)
{
$this->_renderParameters = array_merge($this->_renderParameters,
$parameters);
}
protected function getRenderParameters()
{
return $this->_renderParameters;
}
public function renderWithParams($fileName, $parameters = array())
{
$previousParameters = $this->getRenderParameters();
$this->addRenderParameters($parameters);
// call real render() method
$content = $this->render($fileName);
// reset parameters
$this->setRenderParameters($previousParameters);
return $content;
}
}
----------------------
And then I can have a template to include another template with parameters:
----------------------
<div id="top">
<?php
$header = $this->renderWithParams('header.phtml', array('showLogo'
=> true));
echo $header;
?>
</div>
<div>
some other content
</div>
----------------------
And in "header.phtml":
----------------------
<?php
$params = $this->getRenderParameters();
if(isset($params['showLogo']) && $params['showLogo'] === true)
{
?>
/img/logo.jpg
<?php
}
?>
<div>
some other content
</div>
----------------------
Did I reinvented the wheel? Is there something I didn't see?
Thanks in advance!
--
View this message in context: http://n4.nabble.com/Passing-parameters-to-view-scripts-tp1565353p1565353.html
Sent from the Zend MVC mailing list archive at Nabble.com.
没有评论:
发表评论