This article illustrates the method of thinkphp implementing dynamic inclusion files. Share to everyone for your reference. The specific analysis is as follows:
Problem Description: In the project when the problem encountered, is also a common problem, the General home page contains the head and footsteps, in order to facilitate management, these need to use the inclusion of files to implement, Thinkphp provides a method of including files, the above is the simplest way to include the operation, but in the process of running I found that When the request is only requested is the template file, that is, the so-called static contains, but if you encounter the menu is dynamically generated it is difficult to do.
Find a solution on the Web: using widgets
1, we implement a category display widget in the page, first we want to implement we first define a widget controller layer catewidget, as follows:
Copy Code code as follows:
Class Catewidget extends Action {
Public Function menu () {
Return ' Menuwidget ';
}
}
Note that the definition in the widget package is different from the general action
2, then, we call this widget through the R method in the template (Extended widget mode is used in the stencil is the W method), if the R function does not understand the reference here. (http://www.thinkphp.cn/info/134.html)
{: R (' Cate/menu ', ', ' Widget ')}
The output after execution is: Menuwidget
3, if the Catewidget class's menu method is changed to:
Copy Code code as follows:
Class Catewidget extends Action {
Public Function menu () {
Echo ' Menuwidget ';
}
}
4, template in the use of the need to be changed to:
Copy Code code as follows:
{~r (' cate/menu ', ', ', ' Widget ')}
5. If you need to use parameters when invoking the widget, you can define this:
Copy Code code as follows:
Class Catewidget extends Action {
Public Function menu ($id, $name) {
echo $id. ': $name;
}
}
6, template in the parameters of the call, use:
Copy Code code as follows:
{: R (' Cate/menu ', Array (5, ' thinkphp '), ' Widget ')}
Will output the 5:thinkphp
7, to a more complex example:
Copy Code code as follows:
Class Catewidget extends Action {
Public Function menu () {
$menu = M (' Cate ')->getfield (' Id,title ');
$this->assign (' menu ', $menu);
$this->display (' Cate:menu ');
}
}
8, Catewiget class rendering a template file tpl/cate/menu.html, the flexibility of the call template is also the use of this way to achieve the difference between widgets (the widget extension method needs to invoke the RenderFile method rendering template).
Usage in menu.html template file: {$key}:{$title}
I hope this article will be helpful to everyone's thinkphp framework program design.