This article mainly introduces the usage of widget extension in thinkPHP, and analyzes the usage tips and precautions of widget extension in the form of examples, for more information about how to use widgets in thinkPHP, see the following example. We will share this with you for your reference. The details are as follows:
Widget extension is used to output different content on the page as needed. The definition of Widget extension is to define the Widget class library under the Lib \ Widget Directory of the project, for example, the following defines a Widget for displaying recent comments:
Located in Lib \ Widget \ ShowCommentWidget. class. php
The Widget class library must inherit the Widget class and define the render method implementation. for example:
The render method must use return to return the string to be output, rather than directly output the string.
Widgets can also call the renderFile method of the Widget class to output the template after rendering.
Create a widget Directory under the lib Directory of the project, which is the same as the action directory.
Create TestWidget. class. php:
class TestWidget extends Widget{ public function render($data){ //print_r($data); $data['id']=$data['id']; $data['info']=$data['info']; $content = $this->renderFile('index',$data); //print_r($content); return $content; }}
Create the corresponding Test folder under this directory, and put the html page called by $ this-> rendFile below.
Index.html displays data information cyclically.
This is the template page called by the widget.
// Note: the id corresponds to the $ data key {$ vo}
// Info corresponds to the key value of $ data
{$ V}
Action method:
IndexAction. class. php
The code is as follows:
class TestAction extends Action{ public function index(){ $info=array(array("1","AA","title"),array("2","BB","title2")); $this->assign("info",$info); $this->display(); }}
The HTML page in the tplused for actioncall is index.html.
The code is as follows:
This is the action called by test.
{: W ('test', array ("id" => array ("ID", "name", "title"), "info" => $ info ))} // pass it to TestWidget. class. php parameters must be passed in array format
Run IndexAction. class. php
The page is displayed as follows:
In this case, the content in show.html is included.
When does name use widgte?
Widgets are usually encapsulated JS effect components. you can directly call 'add parameters to obtain some effects, such as interactive effects such as TAB menus, Carousel Trojans, and image carousel.
For example, the menu bar of a website. Columns that are not updated on the right...
It is convenient to call multiple times. for example, a news list is displayed on the left side of the page. if every page calls this list, do you have to write the same code in each controller, the widget may only need to be written once, and then used multiple times in the template
I hope this article will help you design PHP programs based on the thinkPHP framework.