这是一种手动操作 js 和 css 文件资产顺序的方法。
首先,在控制器中添加 css 和 js 路径时,使用自动 Phalcon\Assets\Collection 容器来存储您的临时资产:
$this->assets->addJs('js/bootstrap-multiselect.js');
$this->assets->addCss('css/bootstrap-multiselect.css');
在所有控制器扩展的自定义 BaseController 中,添加一个 afterExecuteRoute() 公共方法:
/**
* stuff to do after a route has been executed
* this is where we attach standard js and css assets
* */
public function afterExecuteRoute(){
// wait to rebuild assets until after the dispatcher is finished
if( ! $this->dispatcher->isFinished() ){
return;
}
...
}
一旦我们确定当前路由已完成执行,我们可以从 Phalcon\Assets\Manager 中的自动 js 和 css 集合中提取临时资产,将它们附加到我们的常见资产文件列表中,对它们进行排序和去重,然后将它们放入新的自定义集合中:
// get list of js files added to the standard js collection
$append_js = array();
forEach( $this->assets->getJs() as $js){
$append_js[] = $js->getPath();
}
// declare paths to common js assets
$js_assets = array(
'js/jquery-2.1.1.min.js',
'js/jquery-ui.min.js',
'js/bootstrap.min.js',
);
// merge common paths with ad-hoc paths
$js_assets = array_merge( $js_assets, $append_js );
$js_assets = array_unique( $js_assets ); // dedup
// add js assets to a new collection
$js_collection = $this->assets->collection('header_js');
forEach( $js_assets as $js_path ){
$js_collection->addJs( $js_path );
}
将 css 资源重新构建到新集合中的工作方式相同:
// get list of css files added to the standard css collection
$append_css = array();
forEach( $this->assets->getCss() as $css ){
$append_css[] = $css->getPath();
}
// declare paths to common css assets
$css_assets = array(
'css/jquery-ui.min.css',
'css/jquery-ui.theme.min.css',
'css/jquery-ui.structure.min.css',
'css/bootstrap.min.css',
'css/bootstrap-theme.min.css',
'css/main.css',
);
// merge common paths with ad-hoc paths
$css_assets = array_merge( $css_assets, $append_css );
$css_assets = array_unique( $css_assets ); // dedup
// add css assets to a new collection
$css_collection = $this->assets->collection('header_css');
forEach( $css_assets as $css_path ){
$css_collection->addCss( $css_path );
}
最后,当您在模板中输出 js 和 css 资产时,输出新的自定义集合,而不是 Phalcon\Assets\Manager 自动创建的默认集合:
{{ getDoctype() }}
<html>
<head>
{{ tag.getTitle() }}
{{ assets.outputCss( 'header_css' ) }}
{{ assets.outputJs( 'header_js' ) }}
</head>