php 在 Yii2 的其他地方渲染视图 - 没有 renderPartial?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32037557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:46:02  来源:igfitidea点击:

Rendering views in other places in Yii2 - no renderPartial?

phpyiiyii2

提问by Brett

I need to render a partial view inside a custom component file in Yii2and according to the Yii docsyou can access the view instance via something like this:

我需要在自定义组件文件中渲染局部视图Yii2,根据Yii 文档,您可以通过以下方式访问视图实例:

\Yii::$app->view->renderFile('@app/views/site/license.php');

I went ahead and tried:

我继续尝试:

Yii::$app->view->renderPartial('//my/view/');

...but then got an error that I was trying to access a non-existent method.

...但后来得到一个错误,我试图访问一个不存在的方法。

I then checked out the view classand noticed it doesn't have a renderPartialand this is a method of the controllerclass instead.

然后我检查了视图类,发现它没有 a renderPartial,而是控制器类的一个方法。

I see it has a renderFilemethod and a rendermethod; which of these should I use?

我看到它有一个renderFile方法和一个render方法;我应该使用哪些?

The docs don't state the rendermethod includes the layout like the method of the same name from the controllerclass, so I'm not sure; as for renderFileI'm not 100% sure if that is suitable either?

文档没有说明该render方法包括布局,如控制器类中的同名方法,所以我不确定;至于renderFile我也不是 100% 确定这是否合适?

Could someone explain which method would produce the same results that renderPartialproduces?

有人能解释一下哪种方法会产生与产生相同的结果renderPartial吗?

回答by Tony

You can call renderPartialfrom Yii::$app->controller->renderPartial('myview');Also as you can see from source code of yii\base\ControllerrenderPartialcalls View's rendermethod so you can use Yii::$app->view->render. Basically there is no difference between renderand renderFile, because renderinternally calls renderFile. But when you use renderyou can pass $viewin several formats like path alias, absolute path whithin applicationor whithin moduleand relative path. And to renderFileyou can pass only absolute file path or path alias.

您可以renderPartialyii\base\Controller 的源代码中Yii::$app->controller->renderPartial('myview');也可以看到调用 View 的方法,因此您可以使用. 和之间基本上没有区别,因为在内部调用. 但是当您使用时,您可以传入多种格式,例如路径别名应用程序的绝对路径模块相对路径。并且您只能传递绝对文件路径或路径别名。renderPartialrenderYii::$app->view->renderrenderrenderFilerenderrenderFilerender$viewrenderFile