Yii2 assets註冊的css樣式文件沒有加載

準備引入layui.css文件的,在LayuiAssets類中已經配置了資源屬性

<?php

namespace frontend\assets;

use yii\web\AssetBundle;

class LayuiAsset extends AssetBundle
{
    public $sourcePath =  "@frontend/assets/app";

    public $js = [
        'layer.js',
        'layui.js',
    ];

    public $css = [
        'css/layui.css'
    ];

    public $jsOptions = ['position' => \yii\web\view::POS_HEAD];
    
    public $depends = [
        'yii\web\JqueryAsset',
    ];
}

但是,打開網頁沒有引入,發現目錄下已經發布了css樣式文件,原來yii2 在加載css 的資源文件時,會註冊時會生成對應的link標籤,但是還未加入網頁中,引入文件是通過layout中生成一個佔位符常量,例如

const PH_HEAD = '<![CDATA[YII-BLOCK-HEAD]]>';

然後通過strtr函數對佔位符進行替換,換成對應的的代碼:

public function endPage($ajaxMode = false)
    {
        $this->trigger(self::EVENT_END_PAGE);

        $content = ob_get_clean();

        echo  strtr($content, [
            self::PH_HEAD => $this->renderHeadHtml(),
            self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(),
            self::PH_BODY_END => $this->renderBodyEndHtml($ajaxMode),
        ]);

        $this->clear();
    }

renderHeadHtml這個方法時在頁面結束的時候進行佔位符替換,將頭部佔位符換成成對應註冊的css和js代碼。如下是生成link標籤的函數

    /**
     * Renders the content to be inserted in the head section.
     * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
     * @return string the rendered content
     */
    protected function renderHeadHtml()
    {
        $lines = [];
        if (!empty($this->metaTags)) {
            $lines[] = implode("\n", $this->metaTags);
        }

        if (!empty($this->linkTags)) {
            $lines[] = implode("\n", $this->linkTags);
        }
        if (!empty($this->cssFiles)) {
            $lines[] = implode("\n", $this->cssFiles);
        }
        if (!empty($this->css)) {
            $lines[] = implode("\n", $this->css);
        }
        if (!empty($this->jsFiles[self::POS_HEAD])) {
            $lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]);
        }
        if (!empty($this->js[self::POS_HEAD])) {
            $lines[] = Html::script(implode("\n", $this->js[self::POS_HEAD]), ['type' => 'text/javascript']);
        }

        return empty($lines) ? '' : implode("\n", $lines);
    }

但是並沒有引入,如果需要引入,需要生成佔位符即可,所以之前的css未引入的問題,只要在layout的頭部添加一個<?= $this -> head() ?>就好了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章