如何在 YII2 中不渲染某些东西而回显某些东西
How to echo something without rendering something in YII2
我想在操作页面中回应一些内容。
假设我想在 yii 布局中回显 hello word
。
我所知道的是将 hello word 写入文件(hello.php 在视图中)并使用 $this->render('hello');
那么如何让它更短,比如 $this->echo('hello word');
,这样 YII 就会在布局中显示 hello word
?
渲染 HTML 视图不是必需的。这 2 个操作应输出消息:
public function actionHello()
{
echo 'hello word !';
}
public function actionHello2()
{
return 'hello word !';
}
事实上,用于 REST api 的内置 yii\rest\Controller
及其子 ActiveController
返回数据的方式与第二个示例中的方式相同 actionHello2()
.除了他们使用 ContentNegotiator 过滤器输出 JSON and/or XML 而不是纯文本:
'contentNegotiator' => [
'class' => \yii\filters\ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
],
如果您需要在没有主布局的情况下呈现动作视图,您可以使用 renderPartial:
public function actionAbout()
{
echo 'hello word !';
return $this->renderPartial('about');
}
如果您需要渲染主布局和输出数据而不渲染动作视图,您可以使用 renderContent:
public function actionHello()
{
return $this->renderContent('hello word !');
}
更多渲染选项也可以在相关 docs 中找到。
我想在操作页面中回应一些内容。
假设我想在 yii 布局中回显 hello word
。
我所知道的是将 hello word 写入文件(hello.php 在视图中)并使用 $this->render('hello');
那么如何让它更短,比如 $this->echo('hello word');
,这样 YII 就会在布局中显示 hello word
?
渲染 HTML 视图不是必需的。这 2 个操作应输出消息:
public function actionHello()
{
echo 'hello word !';
}
public function actionHello2()
{
return 'hello word !';
}
事实上,用于 REST api 的内置 yii\rest\Controller
及其子 ActiveController
返回数据的方式与第二个示例中的方式相同 actionHello2()
.除了他们使用 ContentNegotiator 过滤器输出 JSON and/or XML 而不是纯文本:
'contentNegotiator' => [
'class' => \yii\filters\ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
],
如果您需要在没有主布局的情况下呈现动作视图,您可以使用 renderPartial:
public function actionAbout()
{
echo 'hello word !';
return $this->renderPartial('about');
}
如果您需要渲染主布局和输出数据而不渲染动作视图,您可以使用 renderContent:
public function actionHello()
{
return $this->renderContent('hello word !');
}
更多渲染选项也可以在相关 docs 中找到。