How do i add scripts and stylesheets inside yii module

不羁岁月 提交于 2019-12-21 20:36:09

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/12969358/how-do-i-add-scripts-and-stylesheets-inside-yii-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!