将 php 代码放在 yii 框架的 registerScript 里面
Put php code inside of registerScript of yii framework
我想在 yii1
的 Yii::app()->clientScript->registerScript
里面放一个 php 代码
我怎样才能把它放在这个里面?
<?php Yii::app()->clientScript->registerScript("form", <<<JAVASCRIPT
// I want the PHP code inside of this
JAVASCRIPT, CClientScript::POS_END); ?>
除了在代码中间结束PHP,还有什么办法吗?
编辑
如果我把 <?PHP ?>
放在中间,我会得到一个
的错误
Parse error: syntax error, unexpected end of file in
C:\xampp\htdocs\yii\project\protected\views\group_Form.php
on line 275
那一行是
JAVASCRIPT, CClientScript::POS_END); ?>
由于您可以在视图上下文中通过 $this
访问控制器实例,我建议您这样做:
创建部分视图 php 文件,您可以在其中构建您的 mixin (js + php),它显然将包含任何脚本类型,并且在 [=34 之上具有某些条件=].
在视图上下文中使用 CBaseController#renderPartial
(实际上 returns 字符串而不是渲染,根据第 3 个参数 return = true
)将 mixin 视图内容作为字符串获取并将其作为第二个参数传递给 Yii::app()->clientScript->registerScript
.
实现如下所示:
// _partial_view.php
// here is your mixin between js + php
/* @var $this CController */
<?php
echo '<script>' .
Yii::app()->user->isGuest
? 'alert("you\'re guest")'
: 'alert("you\'re logged user")'
. '</script>';
然后返回注册 js 调用:
<?php Yii::app()->clientScript
->registerScript("form",
$this->renderPartial('_partial_view.php', [], true), // setting 3rd parameter to true is crucial in order to capture the string content instead of rendering it into the view
CClientScript::POS_END); ?>
我想在 yii1
的Yii::app()->clientScript->registerScript
里面放一个 php 代码
我怎样才能把它放在这个里面?
<?php Yii::app()->clientScript->registerScript("form", <<<JAVASCRIPT
// I want the PHP code inside of this
JAVASCRIPT, CClientScript::POS_END); ?>
除了在代码中间结束PHP,还有什么办法吗?
编辑
如果我把 <?PHP ?>
放在中间,我会得到一个
Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\yii\project\protected\views\group_Form.php on line 275
那一行是
JAVASCRIPT, CClientScript::POS_END); ?>
由于您可以在视图上下文中通过 $this
访问控制器实例,我建议您这样做:
创建部分视图 php 文件,您可以在其中构建您的 mixin (js + php),它显然将包含任何脚本类型,并且在 [=34 之上具有某些条件=].
在视图上下文中使用
CBaseController#renderPartial
(实际上 returns 字符串而不是渲染,根据第 3 个参数return = true
)将 mixin 视图内容作为字符串获取并将其作为第二个参数传递给Yii::app()->clientScript->registerScript
.
实现如下所示:
// _partial_view.php
// here is your mixin between js + php
/* @var $this CController */
<?php
echo '<script>' .
Yii::app()->user->isGuest
? 'alert("you\'re guest")'
: 'alert("you\'re logged user")'
. '</script>';
然后返回注册 js 调用:
<?php Yii::app()->clientScript
->registerScript("form",
$this->renderPartial('_partial_view.php', [], true), // setting 3rd parameter to true is crucial in order to capture the string content instead of rendering it into the view
CClientScript::POS_END); ?>