Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Block in Yii2

Tags:

php

yii

yii2

I have been trying to learn about Block in Yii2 from Yii2 guide. In the block section, I have found some code like:

<?php $this->beginBlock('block1'); ?>

...content of block1...

<?php $this->endBlock(); ?>

I am trying to implement this code and put it into a view file but not getting result or output because I am new with this things and do not understand how to use it. Can you tell me someone what is Block, how to use it and why we should use it.

like image 479
StreetCoder Avatar asked Mar 08 '15 22:03

StreetCoder


1 Answers

The block class extends the Yii widget class for one single purpose. To allow returning of a 'block of code' as a string instead of displaying inline.

This can be useful for example if you want to re-use several times, a piece of html which is generated at run-time.

Implementation

To declare a part of code in a view as a block, first surround it by begin and end statements as suggested in the question with an appropriate name

<?php $this->beginBlock('myblock') ?>
...<div>your html & php mixed code here</div>....
<?php $this->endBlock() ?>

( you may addditionally pass a 2nd parameter as true to begin block if you need to display it in the original location as well)

Next you can use that named block anywhere in the same view or a child view as many times as you like

echo $this->blocks['myblock'] 
like image 129
arkoak Avatar answered Sep 21 '22 22:09

arkoak