简体   繁体   English

在Yii Framework中包含CSS,javascript文件

[英]Include CSS,javascript file in Yii Framework

How to include a Javascript or CSS file in Yii Framework? 如何在Yii Framework中包含Javascript或CSS文件?

I want to create a page on my site that has a little Javascript application running, so I want to include .js and .css files in a specific view. 我想在我的网站上创建一个运行少量Javascript应用程序的页面,所以我想在特定视图中包含.js.css文件。

Something like this: 像这样的东西:

<?php  
  $baseUrl = Yii::app()->baseUrl; 
  $cs = Yii::app()->getClientScript();
  $cs->registerScriptFile($baseUrl.'/js/yourscript.js');
  $cs->registerCssFile($baseUrl.'/css/yourcss.css');
?>

你可以通过添加来实现

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/script');

I liked to answer this question. 我喜欢回答这个问题。

Their are many places where we have css & javascript files, like in css folder which is outside the protected folder, css & js files of extension & widgets which we need to include externally sometime when use ajax a lot, js & css files of core framework which also we need to include externally sometime. 他们在很多地方我们都有css和javascript文件,比如css文件夹里面的受保护文件夹,css&js文件的扩展名和小部件,我们需要在外面包含一些时候使用ajax很多,js和css文件的核心框架,我们也需要在某个时候外部包含。 So their are some ways to do this. 所以他们有一些方法可以做到这一点。

Include core js files of framework like jquery.js, jquery.ui.js 包括jquery.js,jquery.ui.js等框架的核心js文件

<?php 
Yii::app()->clientScript->registerCoreScript('jquery');     
Yii::app()->clientScript->registerCoreScript('jquery.ui'); 
?>

Include files from css folder outside of protected folder. 在受保护文件夹之外的css文件夹中包含文件。

<?php 
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/example.css');
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/css/example.js');
?>

Include css & js files from extension or widgets. 包含扩展或小部件中的css和js文件。

Here fancybox is an extension which is placed under protected folder. 这里fancybox是一个放在受保护文件夹下的扩展名。 Files we including has path : /protected/extensions/fancybox/assets/ 我们包含的文件有路径: / protected / extensions / fancybox / assets /

<?php
// Fancybox stuff.
$assetUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.fancybox.assets'));
Yii::app()->clientScript->registerScriptFile($assetUrl.'/jquery.fancybox-1.3.4.pack.js'); 
Yii::app()->clientScript->registerScriptFile($assetUrl.'/jquery.mousewheel-3.0.4.pack.js'); 
?>  

Also we can include core framework files: Example : I am including CListView js file. 我们还可以包含核心框架文件:示例:我包含CListView js文件。

<?php
$baseScriptUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets'));
Yii::app()->clientScript->registerScriptFile($baseScriptUrl.'/listview/jquery.yiilistview.js',CClientScript::POS_END);  
?>
  • We need to include js files of zii widgets or extension externally sometimes when we use them in rendered view which are received from ajax call, because loading each time new ajax file create conflict in calling js functions. 当我们在渲染视图中使用它们从ajax调用接收时,我们需要在外部包含zii小部件或扩展的js文件,因为每次新的ajax文件在调用js函数时都会产生冲突。

For more detail Look at my blog article 有关更多详细信息请查看我的博客文章

Easy in your conf/main.php. 在conf / main.php中很容易。 This is my example with bootstrap. 这是我的bootstrap示例。 You can see that here 你可以看到, 在这里

'components'=>array(
    'clientScript' => array(
        'scriptMap' => array(
            'jquery.js'=>false,  //disable default implementation of jquery
            'jquery.min.js'=>false,  //desable any others default implementation
            'core.css'=>false, //disable
            'styles.css'=>false,  //disable
            'pager.css'=>false,   //disable
            'default.css'=>false,  //disable
        ),
        'packages'=>array(
            'jquery'=>array(                             // set the new jquery
                'baseUrl'=>'bootstrap/',
                'js'=>array('js/jquery-1.7.2.min.js'),
            ),
            'bootstrap'=>array(                       //set others js libraries
                'baseUrl'=>'bootstrap/',
                'js'=>array('js/bootstrap.min.js'),
                'css'=>array(                        // and css
                    'css/bootstrap.min.css',
                    'css/custom.css',
                    'css/bootstrap-responsive.min.css',
                ),
                'depends'=>array('jquery'),         // cause load jquery before load this.
            ),
        ),
    ),
),

In the view, add the following: 在视图中,添加以下内容:

<?php  
  $cs = Yii::app()->getClientScript();
  $cs->registerScriptFile('/js/yourscript.js', CClientScript::POS_END);
  $cs->registerCssFile('/css/yourcss.css');
?>

Please notice the second parameter when you register the js file, it's the position of your script, when you set it CClientScript::POS_END, you let the HTML renders before the javascript is loaded. 当你注册js文件时,请注意第二个参数,它是你的脚本的位置,当你设置它CClientScript :: POS_END时,你让HTML在加载javascript之前呈现。

Do somthing like this by adding these line to your view files; 通过将这些行添加到您的视图文件来做这样的事情;

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/javascript/file');
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/path/to/css/file');

To include JS and CSS files in a specific view you can do it via controller by passing the parameters false, true , which will include the CSS and JS for, eg: 要在特定视图中包含JS和CSS文件,您可以通过传递参数false, true来执行它,这将包括CSS和JS,例如:

$this->renderPartial(
    'yourviewname',
    array(
        'model' => $model,
        false,
        true
    )
);

There are many methods that we can include javascript, css into your Yii App . 有很多方法我们可以在你的Yii应用程序中包含javascript,css Today I will demonstrate three simple and helpul methods. 今天我将展示三种简单和有用的方法。

A simple way to add js, css by editing config/main.php 通过编辑config / main.php添加js,css的简单方法

// application components
  'components'=>array(
         // ...
        'clientScript'=>array(
            'packages'=>array(
                'jquery'=>array(
                    'baseUrl'=>'//ajax.googleapis.com/ajax/libs/jquery/1/',
                    'js'=>array('jquery.min.js'),
                )
            ),
        ),
        // ...
  ),

Using getClientScript 使用getClientScript

Usually, We add in block of code into Controller or layout of your theme 通常,我们将代码块添加到Controller或主题的布局中

$baseUrl = Yii::app()->baseUrl; 
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl.'/js/yourscript.js');
$cs->registerCssFile($baseUrl.'/css/yourcss.css');

Or shorter: 或更短:

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/javascript/file',CClientScript::POS_END);
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/path/to/css/file');

Include core js files 包含核心js文件

Yii::app()->clientScript->registerCoreScript('jquery');     
Yii::app()->clientScript->registerCoreScript('jquery.ui');

Faster Yii API Document: http://yii.codexamples.com/ 更快的Yii API文档:http: //yii.codexamples.com/

here is a good solution to use CDN and offline scripts 这是使用CDN和脱机脚本的好方法

I use this code in every application I build, so you can use this in any app. 我在我构建的每个应用程序中使用此代码,因此您可以在任何应用程序中使用它。

Included Scripts: 包含的脚本:

  • main.css 的main.css
  • main.js main.js
  • jQuery jQuery的
  • jQuery / CD jQuery / CD
  • Bootstrap 3.1 Bootstrap 3.1
  • Bootstrap 3.1 / CDN Bootstrap 3.1 / CDN
  • Fancybox 2 Fancybox 2
  • Fancybox 2 / CDN Fancybox 2 / CDN
  • FontAwesome 4 FontAwesome 4
  • FontAwesome 4 / CDN FontAwesome 4 / CDN
  • Google Analytics Script Google Analytics脚本

STEP1: 步骤1:

put this code in config/main.php 把这段代码放在config / main.php中

        'params'=>array(
            'cdn'=>true, // or false
...

STEP2: 第2步:

create resoreses folder in root app folder and put your script there 在根应用程序文件夹中创建resoreses文件夹并将您的脚本放在那里

res/
--js
--css
--img
--lib
--style
..

STEP3: STEP3:

put this code in components/controller.php 将此代码放在components / controller.php中

public function registerDefaults() 
{
    $cs = Yii::app()->clientScript;

    if (Yii::app()->params['cdn']){
        $cs->scriptMap = array(
            'jquery.js' => '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js',
            'jquery.min.js' => '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js',
        );
        $cs->packages = array(
            'bootstrap' => array(
                'basePath' => 'application.res',
                'baseUrl' => '//netdna.bootstrapcdn.com/bootstrap/3.1.1/',
                'js' => array('js/bootstrap.min.js'),
                'css' => array('css/bootstrap.min.css'),
                'depends' => array('jquery')
            ),
        );
    } else {
        $cs->packages = array(
            'bootstrap' => array(
                'basePath' => 'application.res',
                'baseUrl' => Yii::app()->baseUrl . '/res/lib/bootstrap/',
                'js' => array('js/bootstrap.js'),
                'css' => array('css/bootstrap.css'),
                'depends' => array('jquery')
            ),
        );
    }

    $cs->registerPackage('bootstrap');

    $cs->registerCSSFile(Yii::app()->baseUrl . '/res/style/main.css');
    $cs->registerScriptFile(Yii::app()->baseUrl . '/res/js/main.js');
}

public function registerFancybox($buttons = false, $thumbs = false) 
{
    $cs = Yii::app()->clientScript;

    $cs->packages = array(
        'fancybox' => array(
            'basePath' => 'application.res',
            'baseUrl' => Yii::app()->baseUrl . '/res/lib/fancybox/',
            'js' => array('lib/jquery.mousewheel-3.0.6.pack.js', 'source/jquery.fancybox.pack.js'),
            'css' => array('source/jquery.fancybox.css'),
            'depends' => array('jquery')
        ),
        'fancybox-buttons' => array(
            'basePath' => 'application.res',
            'baseUrl' => Yii::app()->baseUrl . '/res/lib/fancybox/source/helpers/',
            'js' => array('jquery.fancybox-buttons.js'),
            'css' => array('jquery.fancybox-buttons.css'),
        ),
        'fancybox-thumbs' => array(
            'basePath' => 'application.res',
            'baseUrl' => Yii::app()->baseUrl . '/res/lib/fancybox/source/helpers/',
            'js' => array('jquery.fancybox-thumbs.js'),
            'css' => array('jquery.fancybox-thumbs.css'),
        )
    );

    $cs->registerPackage('fancybox');
    if ($buttons)
        $cs->registerPackage('fancybox-buttons');
    if ($thumbs)
        $cs->registerPackage('fancybox-thumbs');
}

public function registerFontAwesome(){

    $cs = Yii::app()->clientScript;

    if (Yii::app()->params['cdn']):
        $cs->packages = array(
            'fontAwesome' => array(
                'basePath' => 'application.res',
                'baseUrl' => '//netdna.bootstrapcdn.com/font-awesome/4.0.0/',
                'css' => array('css/font-awesome.min.css'),
            )
        );
    else:
        $cs->packages = array(
            'fontAwesome' => array(
                'basePath' => 'application.res',
                'baseUrl' => Yii::app()->baseUrl . '/res/lib/font-awesome/',
                'css' => array('/css/font-awesome.min.css'),
            )
        );
    endif;

    $cs->registerPackage('fontAwesome');
}

public function registerGoogleAnalytics()
{
    if($this->config('settings_google_analytics_id')){
        Yii::app()->clientScript->registerScript('GA',"
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

            ga('create', '".Yii::app()->params['cdn']."', '{$_SERVER['SERVER_NAME']}');
            ga('send', 'pageview');
        ");
    }
}

STEP4: 第4步:

call the functions like this in //layouts/main.php 在//layouts/main.php中调用这样的函数

Yii::app()->getController()->registerDefaults();
Yii::app()->getController()->registerFontAwesome();
Yii::app()->getController()->registerGoogleAnalytics();

Also, if you want to add module assets both CSS and JS, you can use the following logic. 此外,如果要添加CSS和JS的模块资产,可以使用以下逻辑。 See how you need to indicate the correct path to getPathOfAlias : 了解如何指示getPathOfAlias的正确路径:

public static function register($file)
{
    $url = Yii::app()->getAssetManager()->publish(
    Yii::getPathOfAlias('application.modules.shop.assets.css'));

    $path = $url . '/' . $file;
    if(strpos($file, 'js') !== false)
        return Yii::app()->clientScript->registerScriptFile($path);
    else if(strpos($file, 'css') !== false)
        return Yii::app()->clientScript->registerCssFile($path);

    return $path;
}

The above code has been taken from GPLed Yii based Webshop app. 上面的代码取自基于GPLed Yii的Webshop应用程序。

You can also add scripts from controller action. 您还可以从控制器操作添加脚本。 Just add this line in an action method then that script will apear only in that view: 只需在操作方法中添加此行,然后该脚本将仅在该视图中显示:

Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl . '/js/custom.js', CClientScript::POS_HEAD);

where POS_HEAD tell framework to put script in head section 其中POS_HEAD告诉框架将脚本放在head部分

In Yii framework, You can include js and css using below method. 在Yii框架中,您可以使用以下方法包含js和css。

Including CSS: 包括CSS:

{Yii::app()->request->baseUrl}/css/styles.css

Including JS: 包括JS:

{Yii::app()->request->baseUrl}/js/script.js

Including Image: 包括图片:

{Yii::app()->request->baseUrl}/images/logo.jpg

Note: By using layout concept in yii, You can add css and js instead of specifying in view template. 注意:通过在yii中使用布局概念,您可以添加css和js,而不是在视图模板中指定。

Add the CSS and JS in The Layout Folder.Access anywhere in the project 在布局文件夹中添加CSS和JS。在项目的任何位置访问

  <!--// Stylesheets //-->
    <?php
        $themepath=Yii::app()->theme->baseUrl;
        Yii::app()->clientScript->registerCoreScript("jquery");
    ?>

        <link href="<?php echo $themepath."/css/custom.css"; ?>" rel="stylesheet" media="all" />


<!--// Javascript //-->
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
</script> -->
<script type="text/javascript" src="<?php echo $themepath; ?>/js/video.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="/news/js/popup.js"></script>

link must input over the first php tag in the view pag link必须通过视图pag中的第一个php标记输入

Using bootstrap extension 使用bootstrap扩展

my css file: themes/bootstrap/css/style.css 我的css文件: themes / bootstrap / css / style.css

my js file: root/js/script.js 我的js文件: root / js / script.js

at theme/bootstrap/views/layouts/main.php theme / bootstrap / views / layouts / main.php

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/styles.css" />

<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/script.js"></script>

This was also an easy way to add script and css in main.php 这也是在main.php中添加脚本和css的简单方法

<script src="<?=Yii::app()->theme->baseUrl; ?>/js/bootstrap.min.js"></script>
<link href="<?=Yii::app()->theme->baseUrl; ?>/css/bootstrap.css" rel="stylesheet" type="text/css">

If you are using Theme then you can the below Syntax 如果您使用的是主题,那么您可以使用以下语法

Yii::app()->theme->baseUrl

include CSS File : 包含CSS文件:

<link href="<?php echo Yii::app()->theme->baseUrl;?>/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">

Include JS File 包括JS文件

<script src="<?php echo Yii::app()->theme->baseUrl;?>/js/jquery-2.2.3.min.js"></script>

If you are not using theme 如果你没有使用主题

Yii::app()->request->baseUrl

Use Like this 使用像这样

<link href="<?php echo Yii::app()->request->baseUrl; ?>/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">
<script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery-2.2.3.min.js"></script>
  • In Yii Assets are declared in engine/assets/Appassets.php This make more easier to manage all your css and js files 在Yii资产中声明在engine / assets / Appassets.php中这使得更容易管理所有css和js文件 在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM