简体   繁体   English

如何将Yii2小部件结果传递给变量

[英]How to pass Yii2 widget result to variable

I am just stuck with the question, how to get result of one widget's executing, and transform it to variable. 我只是想问一个问题,如何获得一个小部件执行的结果,并将其转换为变量。 I have somewhere something like: 我有一个类似的地方:

[
    'label' => 'Images',
    'content' => $contentImages,
],

And I also got a widget: 我也有一个小部件:

<?php OwlCarouselWidget::begin(); ?>

    <div class="item-class"><img src="/img/girl.png" alt="Image 1"></div>
    <div class="item-class"><img src="/img/girl.png" alt="Image 2"></div>
    <div class="item-class"><img src="/img/girl.png" alt="Image 3"></div>

<?php OwlCarouselWidget::end(); ?>

But the question is, how can I get the result of widget as HTML and put it to variable $contentImages ? 但是问题是,如何获取小部件的结果作为HTML并将其放入变量$contentImages

Ok, I just found out how to solve my problem. 好的,我刚刚找到了解决问题的方法。

I put the widget code to a single view page. 我将小部件代码放在单个视图页面上。

Then, in my another view I put this code: 然后,在另一个视图中,我输入以下代码:

function read($file) {
ob_start();
include($file);
$content = ob_get_contents();
ob_end_clean();
return $content; 
}  
    $contentImages = read(__DIR__ .'/widgets/widget-view.php')

Actually I'm not sure, if this solution is secure, but ok. 实际上,我不确定此解决方案是否安全,但是可以。

from within a controller you can get it like this 从控制器内部您可以像这样获得它

$viewParams = [
    'localViewVariable' = 'something'
];

$content = $this->renderPartial('@views/widgets/widget-view', $viewParams);
// or
$content = $this->view->renderPhpFile('/full/path/to/widget.php', $viewParams);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM