简体   繁体   中英

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 ?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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