There's nothing out of the box, but this is relatively easy to achieve. You can implement that logic in the base controller, something along those lines:
abstract class AbstractController extends \Phalcon\Mvc\Controller
{
public function afterExecuteRoute()
{
// Don't want to add assets if the action gets forwarded.
if (!$this->dispatcher->isFinished()) {
return;
}
$controllerName = $this->dispatcher->getControllerName();
$actionName = $this->dispatcher->getActionName();
$path = 'js/' . $controllerName. '/' . $actionName . '.js';
// Defining APPLICATION_PATH global constant is one way of pointing to the root of your application.
// This can be done in your config or index. Alternatively you could add config to your DI and do
// something like DI::getDefault()->getShared('config')->applicationPath.
if (file_exists(APPLICATION_PATH . '/public/' . $path)) {
$this->assets->addJs($path);
} else {
$this->assets->addJs('js/main.js');
}
}
}
And in the view output them as usual:
<html>
<head>
<title>Some amazing website</title>
<?php $this->assets->outputCss() ?>
</head>
<body>
<!-- ... -->
<?php $this->assets->outputJs() ?>
</body>
<html>
Have a look at controller events, they come in really handy at times like this.
Updated
Another possible approach is to tight up the selection of js with the view selection logic. The view will check for views/controller/action.volt
, views/layouts/controller.volt
, etc., read more about hierarchical rendering. This will help to keep things neater by matching the js hierarchy with the actual view hierarchy. It's up to you how you implement this, but it would probably be best to keep it all in the same afterExecuteRoute
handler.