Accessing Action Variables in your Layout

Lately have been spending some of my free time trying to learn zf2. So far I have found there to be quite a steep learning curve, and I am usually good at picking up things quickly. One problem I have encountered while developing a sample app is accessing variables set in the ActionController in my layout.phtml. After some googling I found this great blog post:

http://akrabat.com/zend-framework-2/access-view-variables-in-another-view-model/

However, it did not work for me. When I tried to access the child nodes using:

$children = $this->viewModel()->getCurrent()->getChildren();

I consistently received errors because the method getCurrent() returned null. After a lot of trial and error, my solution was to set the layout variables in the ActionController. For example:

    public function indexAction()
    {
        $myvars = array('myvar' => 'test');
        $this->layout()->setVariables($myvars);
        return array('myvar' => 'test');
    }

While this is a horrible hack, it accomplished my goal. Now in my layout template I can simply use the following to output the variable.

   <?php echo $this->myvar; ?>