视图负责将数据呈现给最终用户。在Web应用程序中,视图只是包含HTML和PHP代码的PHP脚本文件。
步骤1-让我们看一下基本应用程序模板的“关于”视图。
<?php /* @var $this yii\web\View */ use yii\helpers\Html; $this->title = 'About'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-about"> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <code><?= __FILE__ ?></code> </div>
在$此变量是指管理和呈现此视图模板视图组件。
这是“关于”页面的样子:
重要的是编码和/或过滤来自最终用户的数据,以避免XSS攻击。您应该始终通过调用yii \ helpers \ Html :: encode()编码纯文本,并通过调用yii \ helpers \ HtmlPurifier来编码HTML内容。
步骤2-以以下方式修改“关于”视图。
<?php /* @var $this yii\web\View */ use yii\helpers\Html; use yii\helpers\HtmlPurifier; $this->title = 'About'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-about"> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <p> <?= Html::encode("<script>alert('alert!');</script><h1>ENCODE EXAMPLE</h1>>") ?> </p> <p> <?= HtmlPurifier::process("<script>alert('alert!');</script><h1> HtmlPurifier EXAMPLE</h1>") ?> </p> <code><?= __FILE__ ?></code> </div>
步骤3-现在输入http:// localhost:8080 / index.php?r = site / about。您将看到以下屏幕。
注意,Html :: encode()函数中的javascript代码显示为纯文本。对于HtmlPurifier :: process()调用也是如此。仅显示h1标签。
视图遵循这些约定-
要在控制器内渲染视图,可以使用以下方法-
要在另一个视图中呈现一个视图,可以使用以下方法-
步骤4-在views / site文件夹内,创建两个视图文件:_part1.php和_part2.php。
_part1.php –
<h1>PART 1</h1>
_part2.php –
<h1>PART 2</h1>
步骤5-最后,在“关于”视图中渲染这两个新创建的视图。
<?php /* @var $this yii\web\View */ use yii\helpers\Html; $this->title = 'About'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-about"> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <?= $this->render("_part1") ?> <?= $this->render("_part2") ?> <code><?= __FILE__ ?></code> </div>
您将看到以下输出:
渲染视图时,可以使用视图名称或视图文件路径/别名来定义视图。视图名称通过以下方式解析-
要访问视图中的数据,应将数据作为第二个参数传递给视图呈现方法。
步骤1-修改SiteController的actionAbout。
public function actionAbout() { $email = "admin@support.com"; $phone = "+78007898100"; return $this->render('about',[ 'email' => $email, 'phone' => $phone ]); }
在上面给出的代码中,我们传递了两个变量$ email和$ phone以在About视图中呈现。
步骤2-更改关于视图代码。
<?php /* @var $this yii\web\View */ use yii\helpers\Html; $this->title = 'About'; $this->params['breadcrumbs'][] = $this->title; ?> <div class = "site-about"> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <p> <b>email:</b> <?= $email ?> </p> <p> <b>phone:</b> <?= $phone ?> </p> <code><?= __FILE__ ?></code> </div>
我们刚刚添加了两个从SiteController接收到的变量。
步骤3-在网络浏览器中输入URL http:// localhost:8080 / index.php?r = site / about,您将看到以下内容: