Как в YII2 конвертировать string в html при передаче кода виджета во view?

День добрый!
Имеются входящие данные в виде дерева массивов:
spoiler

Array
(
    [11] => Array
        (
            [id] => 11
            [name] => one
            [description] => first
            [child] => Array
                (
                    [33] => Array
                        (
                            [id] => 33
                            [name] => three
                            [description] => third
                        )
                )
        )
    [22] => Array
        (
            [id] => 22
            [name] => two
            [description] => second
            [child] => Array
                (
                    [11] => Array
                        (
                            [id] => 11
                            [name] => one
                            [description] => first
                            [child] => Array
                                (
                                    [33] => Array
                                        (
                                            [id] => 33
                                            [name] => three
                                            [description] => third
                                        )
                                )
                        )
                    [33] => Array
                        (
                            [id] => 33
                            [name] => three
                            [description] => third
                        )
                )
        )
    [33] => Array
        (
            [id] => 33
            [name] => three
            [description] => third
        )
)


Их обрабатывает в модели сей код:
spoiler

private function getChildsForView($child){
        $this->list .= 'Collapse::widget([\'items\' => [';
        foreach($child as $k => $v){
            $this->list .= '[
                    \'label\' => \'' . $v['name'] . ' - ' . $v['description'] . '\'';
            $this->list .= ',\'content\' =>  ';
            if(isset($v['child'])) {
                $this->list .= self::getChildsForView($v['child']);
            } else $this->list .= '\'\',]';
            $this->list .= ',],';
        }
        $this->list .= '])';
    }


Я хочу завернуть данные в виджет бутстрапа Collapse, получая на выходе такой код:
spoiler

Collapse::widget(
   [
      'items' => [
            [ 
                  'label' => 'one - first',
                  'content' => Collapse::widget(
                        [
                              'items' => [
                                    [ 
                                          'label' => 'three - third',
                                          'content' => '',
                                    ],
                              ],
                        ]),
            ],
            [ 
                  'label' => 'two - second',
                  'content' => Collapse::widget(
                        [
                              'items' => [
                                    [ 
                                          'label' => 'one - first',
                                          'content' => Collapse::widget(
                                                [
                                                      'items' => [
                                                            [ 
                                                                  'label' => 'three - third',
                                                                  'content' => '',
                                                            ],
                                                      ],
                                                ]),
                                    ],
                                    [ 
                                          'label' => 'three - third',
                                          'content' => '',
                                    ],
                              ],
                  ]),
            ],
            [ 
                  'label' => 'three - third',
                  'content' => '',
            ],
      ],
]);


Однако когда он передаётся во view - он воспринимает непосредственно как текст и не выводит виджет как таковой вообще, выводя просто этот текст. Однако если просто взять текст переменной и его через echo вывести - то всё нормально воспринимается: 5d49a33a7252462898f4f1ef853c1b0b.png

Вопрос - как насильно заставить YII2 интерпретировать мою переменную с кодом НЕ как текст, а как код?
ЗЫ: html_entity_decode, htmlspecialchars_decode не помогают.
  • Вопрос задан
  • 955 просмотров
Решения вопроса 1
iiifx
@iiifx
PHP, OOP, SOLID, Yii2, Composer, PHPStorm
О боги! А поддерживать потом как, с гадалкой?

Да вынесите вы все это в отдельный специально созданный виджет. Логику разместите в методах класса виджета и формируйте вывод непосредственно во вьюхе виджета. Это же в разы проще и понятнее...

Используем созданный виджет в нужной вьюхе:
<?= \path\to\widget\MyWidget::widget( [ 'list' => $treeList ] ); ?>


Виджет в себе содержит все необходимые методы:
class MyWidget extends \yii\bootstrap\Widget
{
    public $list = [];

    public function someMethod () {}

    public function run () {
        return $this->renderFile( '...' );
    }
}


И собственно вьюха виджета:
<?php
use path\to\widget\MyWidget;
use yii\web\View;

/**
 * @var View     $this
 * @var MyWidget $widget
 */

$widget = $this->context;
?>

<!-- Тут мы используя циклы и методы виджета формируем отображение -->

<?php foreach( $widget->... as $value ) { ?>

    <!-- Делаем что нужно и как нужно -->

<?php } ?>
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
ANTVirGEO
@ANTVirGEO Автор вопроса
spoiler
private function getChildsForView($child){
        $this->c++;
        foreach($child as $k => $v){
            $this->list .= '<div class="panel panel-default">';
                $this->list .= '<div class="panel-heading tick" role="tab" id="heading' . $this->c . '" style="cursor: pointer" data-toggle="collapse" data-parent="#accordion" href="#collapse' . $this->c . '" aria-controls="collapse' . $this->c . '">';
                    $this->list .= '<h4 class="panel-title">';
                        $this->list .= '<img align="middle" id="greentick" src="../images/greenTick.png" class="greenTick" style="display: none">';
                        $this->list .= $v['name'];
                        if(isset($v['child']) && count($v['child']) > 0) $this->list .= ' ' . Html::badge(count($v['child']));
                    $this->list .= '</h4>';
                $this->list .= '</div>';
                if(isset($v['child']) && count($v['child']) > 0){
                    $this->list .= '<div id="collapse' . $this->c . '" class="panel-collapse collapse out" role="tabpanel" aria-labelledby="heading' . $this->c . '">';
                        $this->list .= '<div>';
                            $this->list .= '<ul>';
                                foreach($v['child'] as $kk => $vv){
                                    $this->list .= '<li>';
                                    $this->list .= self::getChildsForView($v['child']);
                                    $this->list .= '</li>';
                                }
                            $this->list .= '</ul>';
                        $this->list .= '</div>';
                    $this->list .= '</div>';
                }
            $this->list .= '</div>';
        }
    }

Вот как-то так выглядит итоговый генератор (к комментарии к первому ответу)
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы