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

3600

被折叠的 条评论
为什么被折叠?



