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

Where it is ok to load assets like addJs or addCss?

Hi,

I started to work on a Phalcon project and my question it is, where I can load the Assets like addJs or addCss.

I added this on ControllerBase, something like this:

class ControllerBase extends Controller {

public function onConstruct()
{

  $this->view->setVar('logged_in', is_array($this->auth->getIdentity()));
  $router = $this->router->getControllerName();

  $this->assets->addCss('css/style.css');
  $this->assets->addJs('https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');

  if($router == "users")
  {
     $this->assets->addJs('js/users/index.js');  
  }

  if($router == "articles")
  {
     $this->assets->addJs('js/articles/index.js');  
  }

  if($router == "realtime")
  {
    $this->assets->addJs('js/realtime/index.js');
  }
}

How do you all implement this? I don't know what's the correct way to do this.

Thanks!

Phalcon defers rendering of HTML until the dispatcher is finished with all it's events. That means, you can call addJs / addCss from almost anywhere in your app logic.

(We also use the pattern you've described: a ControllerBase which adds the assets, and all controllers are derived from that, not the base Phalcon one).

If you're after performance info, @Jurigag will most likely have some insight!

edited May '17
if($router == "users")
  {
     $this->assets->addJs('js/users/index.js');  
  }

  if($router == "articles")
  {
     $this->assets->addJs('js/articles/index.js');  
  }

  if($router == "realtime")
  {
    $this->assets->addJs('js/realtime/index.js');
  }

This part you could just move to users/articles/realtime controller part in for example initialize or onConstruct part too. So without ifs, just addJs alone.

I think this is fine way to do this.



77.7k
Accepted
answer
edited May '17

Hmmm... or you could use this in your ControllerBase:

public function onConstruct() {
    $controller = $this->dispatcher->getControllerName();
    // you should first check if the JS file exists...
    $this->assets->addJs('js/'.$controller.'/index.js');
}

Also tbh it will be better for user to load whole js minified and gziped anyway with js code for all pages. It depends really how your website looks like, how many times user will go to certain page etc.



5.7k

Great, thank you guys!