简体   繁体   中英

Assigning variables during render event to phprenderer not passing to layout

i am trying to assign variables to my view renderer during an event i attached to the render event and its not producing values.

I have an event that i attached to the render event in my Application Module . I also have the method which gets called during the render event operation This is a Zend Framework 3 Application however I tagged Zend Framework 2 for more exposure since the framework is very new. Here it is

namespace Application;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $app = $e->getParam('application');
        $app->getEventManager()->attach('render', array($this, 'setAssignRouteVariables'));
    }

    public function setAssignRouteVariables(MvcEvent $e)
    {
        $matches    = $e->getRouteMatch();
        $action     = $matches->getParam('action');
        $controller = $matches->getParam('controller');
        $designHandler = $e->getApplication()->getServiceManager()->get('DesignHandler');   
        $designHandler->getPhprenderer()->controllerName='testcontroller';
        $designHandler->getPhprenderer()->actionName='testaction';
    }
}

If you look, I am calling the method getPhprenderer() using the DesignHandler class. This method returns an instance of \\Zend\\View\\Renderer\\PhpRenderer . In any case after this i assign variables to the renderer object.

Following this, in my layout - application/view/layout/layout.phtml i do this:

<script type="text/javascript">
   var currentController = '<?php echo $this->controllerName;?>';
   var currentAction = '<?php echo $this->actionName;?>';
</script>

I'm getting blank values in this.

What am I doing incorrectly here?

Here's the current result :

    <script type="text/javascript">
       var currentController = '';
       var currentAction = '';
    </script>

This worked.

        public function setAssignRouteVariables(MvcEvent $e)
        {
            $matches    = $e->getRouteMatch();
            $action     = $matches->getParam('action');
            $controller = $matches->getParam('controller');     
            $e->getViewModel()->controllerName=$controller;
            $e->getViewModel()->actionName=$action;
        }

You can use $GLOBALS global variable instead. I faced same problem but did not find better solution.

$GLOBALS["my_index"] = "My value";

in javascript

var myval = '<?=$GLOBALS["my_index"]?>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM