Yii2-View视图里面引入css、js之Block

本文介绍了在Yii2框架中如何优雅地在视图(view)中引入CSS和JS,推荐使用Block方法进行管理。分别展示了创建CssBlock和JsBlock的方式,并在视图页面中的应用。对于JS动态传参,提出了一种通过PHP文件传递参数到JS的解决方案。

Css

第一方式(不常用)

$cssString = "body *{
-webkit-filter: grayscale(100%); /* webkit */
-moz-filter: grayscale(100%); /*firefox*/
-ms-filter: grayscale(100%); /*ie9*/
-o-filter: grayscale(100%); /*opera*/
filter: grayscale(100%);
filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=1); 
filter:gray; /*ie9- */
}";  
$this->registerCss($cssString); 

确定,可读性不好

第二种方式,自己用的比较多,推荐
新建CssBlock.php

use yii\widgets\Block ;

class CssBlock extends Block{

    /**
     * @var null
     */
    public $key = null;
    /**
     * @var int
     */
    public $options = [];
    /**
     * Ends recording a block.
     * This method stops output buffering and saves the rendering result as a named block in the view.
     */
    public function run()
    {
        $block = ob_get_clean();
        if ($this->renderInPlace) {
            throw new \Exception("not implemented yet ! ");
            // echo $block;
        }
        $block = trim($block) ;
        $cssBlockPattern = '|^<style[^>]*>(?P<block_content>.+?)</style>$|is';
        if (preg_match($cssBlockPattern, $block, $matches)) {
            $block = $matches['block_content'];
        }
        $this->view->registerCss($block, $this->options, $this->key);
    }
}

view视图页面引入使用

<?php CssBlock::begin() ?>
<style>
    li{...}
</style>
<?php CssBlock::end() ?>

其实还有其他许多方法,找到适合自己的,用熟了就行

同理,JS也一样,直接写第二种方式
新建JsBlock.php

use yii\web\View ;
use yii\widgets\Block ;

class JsBlock extends Block{

    /**
     * @var null
     */
    public $key = null;
    /**
     * @var int
     */
    public $pos = View::POS_END ;
    /**
     * Ends recording a block.
     * This method stops output buffering and saves the rendering result as a named block in the view.
     */
    public function run()
    {
        $block = ob_get_clean();
        if ($this->renderInPlace) {
            throw new \Exception("not implemented yet ! ");
            // echo $block;
        }
        $block = trim($block) ;
        $jsBlockPattern  = '|^<script[^>]*>(?P<block_content>.+?)</script>$|is';
        if(preg_match($jsBlockPattern,$block,$matches)){
            $block =  $matches['block_content'];
        }

        $this->view->registerJs($block, $this->pos,$this->key) ;
    }
}

view视图页面引入使用

<?php JsBlock::begin() ?>
    <script>
        </script>
<?php JsBlock::end() ?>

遇到JS动态传参,可以使用

echo Yii::$app->view->renderFile(‘'@别名路径/XXJS.php’,$arr);
//

XXJS.php正常的php文件,传参到js里面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值