Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Load assets to all views

So, I have a bunch of controllers and views in a project. And I want to set my assets (CSS and JavaScript) just once instead of replicate it to every controller that have views. How can I do that?

For each new controller that I have I need to put this code to get the assets loaded:

    private function loadAssets($isProduction)
    {
        define("csspath","application/public/css/");
        define("jspath","application/public/js/");

        if($isProduction){
            $this->assets
             ->addCss(csspath.'compiled-output.css');

            $this->assets
             ->addJs(jspath.'compiled-output.js');
        }else{
            $this->assets
             ->addCss(csspath.'bootstrap.min.css', true)
             ->addCss(csspath.'master/styles.dashboard.css', true);

            $this->assets
             ->addJs(jspath.'jquery.min.js', true)
             ->addJs(jspath.'master/module.animations.js', true)
             ->addJs(jspath.'master/module.actions.js', true);
        }
    }

Where can I set this function to load automatically into all my other controllers/views? I've tried IndexController and ControllerBase, but they didn't worked.



1.5k
Accepted
answer
edited Jun '15

You can create a base controller like this:

class ControllerBase extends Controller
{
    private $isJsonResponse = false;

    public function initialize()
    {
        //Javascripts in the header
        $this->assets
            ->collection('headerjs')
            ->addJs('http://static.origos.hu/s/js/modules/jquery-1.11.0.min.js', false)
            ->addJs('http://static.origos.hu/s/js/modules/mustache.min.js', false)
            ->addJs('assets/js/app.js');

        //Css in the header
        $this->assets
            ->collection('headercss')
            ->addCss('assets/css/style.css');
    }
    ....
}

And than you need to extend this ControllerBase from your controllers

Thanks, it worked!