【发布时间】:2015-01-15 18:17:00
【问题描述】:
我有两个模块。
- 应用
- 用户
布局在应用程序模块中设置,在布局中有我需要显示的模块特定的导航元素,这就是我想要做的。
这是我在应用程序模块的layout/layout中调用的部分。
//file: module/Application/view/layout/container/layout.phtml
<?php echo $this->partial('toolbar'); ?>
这是我的 toolbar.phtml
//file: module/Application/view/layout/chunks/toolbar.phtml
<div class="new-top-menu">
<div class="navbar-header">
<a class="navbar-brand sidebar-toggle-box" href="#">
<div class="sidebar-left-trigger">
<span class="fa fa-align-right"></span>
</div>
</a>
</div>
<ul class="nav navbar-nav">
<?php echo $this->placeholder('notification/top-menu'); ?>
</ul>
<ul class="nav navbar-nav navbar-right">
<?php echo $this->placeholder('toolbar/search'); ?>
<?php echo $this->placeholder('toolbar/right-position1')->set($this->position1); ?>
<?php echo $this->placeholder('toolbar/right-position2')->set($this->position2); ?>
<?php echo $this->placeholder('toolbar/right-position3')->set($this->position3); ?>
</ul>
</div>
基本上我想从用户模块中读取另一个名为 toolbar/user-menu.phtml 的部分并将其设置为这个占位符 $this->placeholder('toolbar/right-position3'); 的内容
我尝试在用户模块的 Module.php 中这样做。
namespace User;
public function onBootstrap(MvcEvent $e)
{
$viewModel = $e->getViewModel();
$viewModel->setVariable('position1', 'test string');
}
这工作得很好,问题是我想用位于file: module/User/view/toolbar/user-menu.phtml的部分内容替换内容“测试字符串”
感谢任何关于如何在 ZF2 中完成此操作的指针。
谢谢。
更新1:
我能够使用以下代码做到这一点,无论如何,我期待着这是否可以改进。
在 User/Module.php 中我更新了以下内容。
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver;
public function onBootstrap(MvcEvent $event)
{
$application = $event->getApplication();
$eventManager = $application->getEventManager();
$serviceManager = $application->getServiceManager();
//create a Template Stack
$stack = new Resolver\TemplatePathStack(array('script_paths' => array(__DIR__ . '/view/user/toolbar')));
//create a Resolver
$resolver = new Resolver\AggregateResolver();
$resolver->attach($stack);
//create a Renderer
$renderer = new PhpRenderer();
$renderer->setResolver($resolver);
$viewHelperManager = $serviceManager->get('ViewHelperManager');
$urlViewHelper = $viewHelperManager->get('url');
$partial = $renderer->partial('user-menu', array(
'signOutUrl' => $urlViewHelper('user-account-sign-out')
));
$viewModel = $event->getViewModel();
$viewModel->setVariable('position1', $partial);
}
就是这样,我现在可以将 HTML 内容放在占位符中,我现在面临的唯一问题是访问 user-menu.phtml 文件中的视图帮助程序,我目前正在 Module.php 中生成它和将其传递给视图文件。
【问题讨论】:
-
为什么不创建一个类并将其定义为成员,以便可以重用它?
-
它对我的场景有什么帮助?我在想占位符非常适合我想做的事情,我不确定如何使用独立类来实现。
-
我解决了这个问题,但似乎太乱了,我把代码贴在这里。
-
您可以定义静态成员。您设置成员值并在需要时使用它。
标签: php zend-framework2 partials