How do i add scripts and stylesheets inside yii mo

2020-07-22 10:21发布

i am new to yii. I just created a module in yii the file structure is as follows

 -yii
  -protected
     -modules
        -admin
           -controller
           -model
           -view
               -layout
                    -main.php
           -css
               -style.css
           -images
               -logo.jpg

i was able to set the layout to like this

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

           'admin'=>array(
                 'layoutPath' => 'protected/modules/admin/views/layouts',  ;

)

and now the layout is rendered from the admin module the problem is that i cant load the stylesheets using

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

Does anybody knows the correct way to load stylesheets in yii

标签: php yii
1条回答
放荡不羁爱自由
2楼-- · 2020-07-22 11:08

Everything under your protected folder its indeed, protected, and not public accessible.

in your case, that you are using a module and your files are inside protected folders, your need to 'publish' them to be public accessible. the default public folder for published stuff in Yii its called 'assets'. and to publish we will be using CAssetManager.

First create a folder that contains all your css, js and images that you'd need public access to. name it whatever you want, but the standard its 'assets', so taht your file structure looks like this:

 -yii
  -protected
     -modules
        -admin
           -controller
           -model
           -view
               -layout
                    -main.php
           -assets
               -css
                   -style.css
               -js
               -images
                   -logo.jpg

In your module create a property that will store the public url of the published asset, and a method to access it.

private $_assetsUrl;

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

You can then access your assets like this:

<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>

Further reading

查看更多
登录 后发表回答