Home >Backend Development >PHP Tutorial >ThinkPHP Widget extension example_PHP tutorial
ThinkPHP’s Widget extension is used to output different content according to the needs of the page. It is defined under Lib/Widget in the project directory.
The specific definition is as follows:
class NewsListWidget extends Widget{ public function render($data){ // code... } }
Note:
1. Widget is an abstract class, which has an abstract method (abstract) render, which must be implemented in subclasses;
2. Widget’s render method must use return instead of direct output;
3.$data is the parameter passed into the Widget.
Then we can call this Widget directly in the template:
{:W('NewsList', array('tmpl' => 'a'))}
Here I passed in a parameter. This is a common usage. What is the Widget used for? Different content is output according to the needs of the page. This different content can be different data or, of course, different templates.
class NewsListWidget extends Widget{ public function render($data){ // code $news; // 这里可以是数据检索语句检索出来一个数据集 $html = $this->renderFile($data['tmpl'], $news); return $html; } }
At this time, the content of the template file /Lib/Widget/NewsList/a.html will be automatically rendered, and $news will be sent to it. It can be processed as an ordinary template file and then output.
Of course, you can also obtain the content of the Widget in the Action controller for secondary processing.
$content = W('NewsList', array('tmpl' => 'a'), TRUE); // 第三个参数表示是否返回字符串,默认是FALSE,代表直接输出。
In addition, ThinkPHP is an MVC framework, please put data retrieval related content in the Model layer