There is a view widget

class ItemsWidget extends Widget { public $items; public function init() { parent::init(); $this->items = Items::find()->asArray()->all(); ob_start(); // что-то вроде этого, но не работает for ($i=0; $i < count ($this->items) ; $i++ ) { extract($this->items[$i]); } } public function run() { $content = ob_get_clean(); return Html::encode( $content ); } } 

The view uses the Smarty templating engine, although it doesn’t play a role in this case.

 {ItemsWidget assign='widget'} // как обойтись без цикла здесь ? <div>{$widget.items.title}</div> {/ItemsWidget} 

How can I iterate through the array and return the finished block of code?

  • As I understand it, you use the template engine. Twig documentation on cycles can be found here - NPreston
  • This is smarti. How to display the whole thing in the template engine I’m aware of, just a code like {ItemsWidget assign='widget'} {foreach $widget.items as $item} <div>{$item.title}</div> {/foreach} {/ItemsWidget} somehow confuses me. I understand there is a way to do this in the ItemsWidget.php file - Guest

1 answer 1

As far as I understand, you don’t really understand until the end how the widget works:

For example, in the frontend / widgets folder, I create a Header.php file with some content:

 <?php namespace frontend\widgets; use common\models\Articles; use yii\base\Widget; class Header extends Widget { public function init() { parent::init(); } public function run() { $rows = Articles::find()->all(); return $this->render('header', [ 'rows' => $rows ]); } } 

Those. I got a sample in $ rows and passed it to the template. inside the frontend / widgets I create the views folder and put the header.php file there - this is the template

 <div> <?foreach($rows as $row):?> <p><?=$row->title?></p> <span><?=$row->date_add?></span> <p><?=$row->text?></p> <?endforeach;?> </div> 

In any template, call

 <?= frontend\widgets\Header::widget()?> 

It will be rendered along with the layout, if you need a pure template, without layout, then instead of $ this-> render, you must use $ this-> renderPartial

  • It turns out if for example I need to bring up the menu, I need to take it from the header to the frontend / widgets folder, and in the header itself something like <? = Frontend \ widgets \ CustomMenu :: widget ()? - Guest
  • Yes, you can take it anywhere, you have classes, you inherit from them. I wrote you a ready-made code. - Adobe
  • Ok, thank you. - Guest