如何在yii模块中添加脚本和样式表

har*_*ish 3 php yii

我是yii的新手.我刚刚在yii中创建了一个模块,文件结构如下

 -yii
  -protected
     -modules
        -admin
           -controller
           -model
           -view
               -layout
                    -main.php
           -css
               -style.css
           -images
               -logo.jpg
Run Code Online (Sandbox Code Playgroud)

我能够将布局设置为这样

'modules'=>array(
    // uncomment the following to enable the Gii tool

           'admin'=>array(
                 'layoutPath' => 'protected/modules/admin/views/layouts',  ;
Run Code Online (Sandbox Code Playgroud)

)

现在布局是从管理模块呈现的问题是我无法加载样式表

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/protected/modules/admin/css/reset.css"  media="all">
Run Code Online (Sandbox Code Playgroud)

有没有人知道在yii中加载样式表的正确方法

Asg*_*oth 10

受保护文件夹下的所有内容确实受到保护,而且无法公开访问.

在您的情况下,您使用的是模块,而您的文件位于受保护的文件夹中,您需要"发布"它们以便公开访问.Yii中已发布内容的默认公用文件夹,称为"资产".并且要发布我们将使用CAssetManager.

首先创建一个文件夹,其中包含您需要公共访问的所有css,js和图像.将它命名为您想要的任何名称,但标准为其"资产",因此您的文件结构如下所示:

 -yii
  -protected
     -modules
        -admin
           -controller
           -model
           -view
               -layout
                    -main.php
           -assets
               -css
                   -style.css
               -js
               -images
                   -logo.jpg
Run Code Online (Sandbox Code Playgroud)

在您的模块中,创建一个属性,用于存储已发布资产的公共URL,以及一种访问它的方法.

private $_assetsUrl;

public function getAssetsUrl()
{
    if ($this->_assetsUrl === null)
        $this->_assetsUrl = Yii::app()->getAssetManager()->publish(
            Yii::getPathOfAlias('admin.assets') );
    return $this->_assetsUrl;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样访问您的资产:

<link rel="stylesheet"
         type="text/css"
         href="<?php echo $this->module->assetsUrl; ?>/css/main.css"/>
   ...
   <div id="logo">
   <?php echo CHtml::link(
                 CHtml::image($this->module->assetsUrl.'/images/logo.png'),
                 array('/xxii')); ?>
   </div>
Run Code Online (Sandbox Code Playgroud)

进一步阅读