views:

500

answers:

3

I'm having an issue trying to append a javascript file using headScript()->appendFile('file name') with Zend. I have my layout setup like this:

    <?= $this->headScript()
    ->prependScript( 'BASE_URL = "' . $this->baseUrl() . '";' )
    ->appendFile( $this->baseUrl('js/lib/jquery/jquery-1.4.2.min.js') )
    ->appendFile( $this->baseUrl('js/admin.js') );

?>

Then, in my controller I am trying to append an additional js file only for this page, like:

    $this->view->headScript()->appendFile( 'another/js/file.js' );

This file needs to be appended to what is already setup in the layout. However, this file gets added before the other 'appendFile' files. I've also tried

$this->headScript()->offsetSetFile(999, '/js/myfuncs.js');

But this still adds the file before the other files. This is not how I would expect this to work, especially when using the offsetSetFile method. How can I add this file after the other files? Thanks.

A: 

I've noticed that if I 'prepend' all the files in the layout, I can then use appendFile in my controller and it will appear after them. Unfortunately, then I have to list all my JS files in reverse order in the layout (since they prepend to themselves). I'd really like to keep things in order and just be able to append to my layout stack.

Ryan
A: 

If prepending in the layout file is not good enough, you can either include the files in your bootstrap when you set up your view or you could set up a controller plugin if you need to prepend based on what module is being loaded.

// in your bootstrap
protected function _initHeadScript()
{
    $this->bootstrap('view');
    $view = $this->getResource('view');

    $view->headScript()->appendFile('another/js/file.js');
}

// as a plugin
class My_Plugin_HeadScriptPlugin extends Zend_Controller_Plugin_Abstract
{
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        $view = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view;

        if($request->getModuleName() == 'foo')
        {
            $view->headScript()->appendFile('another/js/file.js');
        }
    }
}
smack0007
A: 

Actually, you don't need get the baseUrl 'cause ZF already does it for you. You just have to pay attention to your path. Do not use the first slash! otherwise ZF will return the remote address.

Just use '$this->_view->headLink()->appendStylesheet('css/main.css');'

Rodrigo Alves