We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Loading Phalcon assets on controller action

Hi,

I have a few JavaScript files that must only be loaded on a specific page, eg.

I dont want to load the commonJs files on the profile/edit page. Can this be done using assets? At the moment I have a collection that loads all my JavaScript files just before the </body> tag.

// Load this on the /index page
$this->assets
        ->collection('commonJs')
        ->addJs('js/vendor/jquery.js')          

Is there a way to only load a specific collection on a route?

// Load this on the /profile/edit page
$this->assets
        ->collection('myJs')
        ->addJs('js/vendor/mine.js')            

Kind Regards



22.8k

Great! I think I solved my problem :)

eg.

class ProfileController extends ControllerBase
{
    public function editAction()
    {
        $js = $this->assets->collection('myJs' );
        $js->addJs('js/TESTTEST.js');    
    }
}


22.8k
edited Feb '15

Just one last thing to add, all my JavaScript and CSS files are loaded in a index.phtml page. Just before the </body> tag. You wil need to outputJs all your collections - but only add the JS files on the controller action when needed.

<!-- Profile Page JavaScript files -->
<?php echo $this->assets->outputJs('profilePageJs'); ?>

Then in your controller actions add the JS files as per normal :

$this->assets->collection('myJs')->addJs('js/TEST.js');
edited Feb '15

Tip: You can add a JS file to a view without creating a collection

$this->assets->addJs('js/TESTTEST.js');

And then just call outputJs() without parameters

echo $this->assets->outputJs();

This is good for adding single specific JS/CSS files to specific views.