Search code examples
zend-frameworkzend-view

Render view in higher script path with Zend Framework


Lets assume the following code within a controller:

$this->view->addScriptPath('dir1/views/scripts');
$this->view->addScriptPath('dir2/views/scripts');
$this->render('index.phtml');

Where dir1/views/scripts contains 2 files:

-index.phtml  
-table.phtml

And dir2/views/scripts:

-table.phtml

Now, it will render the index.phtml in dir1 since dir 2 doesn't have an index.phtml.

Index.phtml looks something like:

<somehtml>
       <?= $this->render('table.phtml') ?>
</somehtml>

This is where the confusion starts for me. I would expect it to render the table.phtml in the last directory added to the script path stack, but it doesn't.
Is there a simple solution/explanation to my problem?


Solution

  • I ended up extending Zend_View and adding the function renderParent:

    class My_View extends Zend_View
    {
        private $_file = null;
    
        private $_name = null;
    
        /**
         * Finds a view script from the available directories.
         *
         * @param $name string The base name of the script.
         * @return void
         */
        protected function _script($name)
        {
            $this->_file = parent::_script($name);
            $this->_name = $name;
    
            return $this->_file;
        }
    
        /**
         * Renders the parent script by looping through all the script paths.
         *
         * @return void
         */
        public function renderParent()
        {
            $scriptPaths = $this->getScriptPaths();
    
            $found = false;
            for ($i = 0; $i < count($scriptPaths); $i++) {
                if ($this->_file == $scriptPaths[$i] . $this->_name) {
                    $found = true;
                } elseif ($found) {
                    if (is_readable($scriptPaths[$i] . $this->_name)) {
                        return $this->_run($scriptPaths[$i] . $this->_name);
                    }
                }
            }
        }
    }