两个布局 如何在其中一个布局中 加载asset时删除某个css或者js?
您好 打开/backend/views/layouts/main.php 你会看到如下内容:
<?php /* @var $this \yii\web\View */ /* @var $content string */ use backend\assets\AppAsset; use yii\helpers\Html; use yii\bootstrap\Nav; use yii\bootstrap\NavBar; use yii\widgets\Breadcrumbs; use common\widgets\Alert; AppAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang="<?= Yii::$app->language ?>"> <head> <meta charset="<?= Yii::$app->charset ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <?= Html::csrfMetaTags() ?> <title><?= Html::encode($this->title) ?></title> <?php $this->head() ?> </head> <body> <?php $this->beginBody() ?> <div class="wrap">
注册css和js是 类 backend\assets\AppAsset 这个asset类完成的,那么,打开这个类
<?php namespace backend\assets; use yii\web\AssetBundle; /** * Main backend application asset bundle. */ class AppAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [ 'css/site.css', ]; public $js = [ ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; }
你如果想去掉 'css/site.css' ,这个css ,直接去掉就可以了。
当然,可能也在于依赖的assets里面。譬如是
'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset'
里面的某一个,这个是Yii的,你可以新建一个Assets,然后重写里面的方法,把想去掉的去掉,然后$depends里面填写你重写的Assets即可。
$depends
看懂了上面的原理,你下面做的是,复制layouts/main.php 成一个新的layout文件,譬如main_2.php 然后按照上面的原理进行修改
然后,你需要在controller中设置当前的layout文件为main_2.php
main_2.php
不是很明白 这样就可以区分 两个布局引用不同的资源包 ? 那要怎么在两个不同的布局引用相应的资源包?
设置layout文件
在yii/base/controller.php文件可以看到:
public function findLayoutFile($view) { $module = $this->module; if (is_string($this->layout)) { $layout = $this->layout; } elseif ($this->layout === null) { while ($module !== null && $module->layout === null) { $module = $module->module; } if ($module !== null && is_string($module->layout)) { $layout = $module->layout; } } if (!isset($layout)) { return false; } if (strncmp($layout, '@', 1) === 0) { $file = Yii::getAlias($layout); } elseif (strncmp($layout, '/', 1) === 0) { $file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1); } else { $file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout; } if (pathinfo($file, PATHINFO_EXTENSION) !== '') { return $file; } $path = $file . '.' . $view->defaultExtension; if ($view->defaultExtension !== 'php' && !is_file($path)) { $path = $file . '.php'; } return $path; }
通过if (is_string($this->layout)) { 可以看到,可以通过在controller中设置类变量$layout 来设置layout文件。
if (is_string($this->layout)) {
$layout
@jingjim #3楼 你重写的方法中,用到那个,你就引入那个,说的这么详细了,还不明白,我也无能为力了,自己琢磨吧
你写一个新的Asset文件来替代 AppAsset,main.php 还是用AppAsset ,你的main_2.php 使用你新建的App2Asset,里面完全自定义。
可以了 ,多谢!! 很强势!!