Widget Extension Instance of ThinkPHP

  • 2021-07-01 06:46:17
  • OfStack

The Widget extension of ThinkPHP, which is defined under Lib/Widget in the project directory, is used to output different content according to page needs.

The specific definitions are as follows:


class NewsListWidget extends Widget{
  public function render($data){
    // code...
  }
}

It should be noted that:

1. Widget is an abstract class with an abstract method (abstract) render, which must be implemented in a subclass;
2. The render method of Widget must be returned using return instead of output directly;
3. $data is the parameter passed in Widget.

Then we can call this Widget directly in the template:


{:W('NewsList', array('tmpl' => 'a'))}

Here I pass in a parameter, which is a common usage. What is Widget used for? According to the page needs to output different content, this different content, can be different data, of course, can also be different templates.


class NewsListWidget extends Widget{
  public function render($data){
    // code
    $news; //  It can be retrieved by data retrieval statement here 1 Data sets 
    $html = $this->renderFile($data['tmpl'], $news);
    return $html;
  }
}

At this time, the contents of template file/Lib/Widget/NewsList/a. html will be automatically rendered, and $news will be transmitted to the past, which can be processed as a normal template file and then output.

Of course, you can also get the content of Widget in Action controller and process it twice.


$content = W('NewsList', array('tmpl' => 'a'), TRUE); //  No. 1 3 Parameters indicate whether to return a string, and the default is FALSE For direct output. 

In addition, ThinkPHP is the framework of MVC, please put the data retrieval related content in Model layer


Related articles: