【问题标题】:Render partial in other module ZF2在其他模块 ZF2 中渲染部分
【发布时间】:2017-10-23 09:19:41
【问题描述】:

在我的项目中,我必须使用模块

  • 模块1
  • 模块2

在模块 1 中,我有一个视图需要渲染模块 2 中的视图,所以我正在做的是:

$this->partial('partials/hello/title.phtml','Module2',array('data' => $data))

似乎我正确调用了视图,但在视图 title.phtml 内部我无法使用数据

未定义变量:/site/src/module/Module2/view/partials/hello/title.phtml 中的数据

我需要添加一些与配置相关的东西吗?

谢谢!

【问题讨论】:

  • 我使用 $data = $this->viewModel()->getCurrent()->data; 解决了这个问题当使用来自其他模块的部分时需要这样做吗?因为直到现在我能够使用 $data 因为我在同一个模块中使用了一个部分

标签: zend-framework2


【解决方案1】:

你没有正确调用它,试试:

$this->partial('partials/hello/title.phtml', array('data' => $data));

见:http://framework.zend.com/manual/2.3/en/modules/zend.view.helpers.partial.html

partial 在不同的模块中这一事实并不重要。必须将模块名称指定为第二个参数只是 ZF1 中的事情。

【讨论】:

    【解决方案2】:

    另一种解决方案是在模块引导程序中添加您自己的视图路径解析器:

    class Module
    {
        /* @var \Zend\ServiceManager\ServiceManager $SM */
        public static $SM;
        /* @var \Zend\EventManager\EventManager $EM */
        public static $EM; 
    
        public function onBootstrap(MvcEvent $e)
        {
            self::$SM = $e->getApplication()->getServiceManager();
            self::$EM = $e->getApplication()->getEventManager();
    
            //change view resolver to resolve views from {Module}/view/{Controller}/{Action}.phtml path
            self::$EM->attach('dispatch', function($e) {
                self::$SM->get('ViewRenderer')->resolver()->attach(
                        new \Engine\View\Resolver\MCA() , 10
                 );
            });
        }
        ....
    

    Resolver 获取一个字符串,必须返回 path 或者 false(如果没有解析),只需编写 resolver 来理解其他模块的路径:

    <?php
    namespace Engine\View\Resolver;
    
    use Zend\View\Renderer\RendererInterface as Renderer;
    
    /**
     * Resolves view scripts based on a stack of paths
     */
    class MCA implements \Zend\View\Resolver\ResolverInterface
    {
        public function resolve($name, Renderer $renderer = null)
        {
            $path = explode('/', $name);
            if (count($path)<3){
                return false;
            }
            $module = array_shift($path);
            $resolvedPath = ROOT_PATH . '/module/'. ucfirst($module) . '/view/' . implode('/', $path). '.phtml';
            if (!file_exists($resolvedPath)){
                return false;
            }
            return $resolvedPath;
        }
    }
    

    可能存在冲突,但您可以调节解析器的优先级(例如 10 个)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多