控制器代码
public function actionIndex(){
//视图需要显示的数据
$hello_str = 'hello God!<script>alert(3)</script>';
//创建一个数组
$data = array();
//把需要传递给视图的数据,放到数组当中
$data['view_hello_str']=$hello_str;
//传送数据到视图文件
return $this->renderPartial('index',$data);
视图代码
<?php
use yii\helpers\Html; //使用的类的命名空间地址 必须
use yii\helpers\HtmlPurifier; //使用的类的命名空间地址 必须
?>
<!-- 避免跨站脚本攻击 用Html::encode转义输出 原样输出 --!>
<h1><?=Html::encode($view_hello_str);?></h1>
视图页显示结果:
hello God!<script>alert(3)</script>
<!-- 避免跨站脚本攻击 用HtmlPurifier::process完全过滤js代码,不输出js代码 --!>
<h1><?=HtmlPurifier::process($view_hello_str);?></h1>
视图页显示结果:
hello God!