This article mainly introduces ThinkPHP's method of implementing dynamic file inclusion, which is a very practical technique in ThinkPHP project development, for more information about how ThinkPHP dynamically contains files, see the examples in this article. Share it with you for your reference. The specific analysis is as follows:
Problem description: it is also a common problem encountered during project creation. Generally, the home page contains headers and footsteps. To facilitate management, these problems must be implemented by using contained files, thinkPHP provides the file inclusion method. The above is the simplest method to include operations. However, during the running process, I found that only the template file is requested during the request, this is also known as static inclusion, but it is difficult to dynamically generate menus.
Find a solution on the Internet: Use Widgets
1. We implement a Widget for classification display on the page. First, we need to define a Widget controller layer CateWidget, as shown below:
The Code is as follows:
Class CateWidget extends Action {
Public function menu (){
Return 'menuwidget ';
}
}
Note that it is defined in the Widget package, which is different from the general Action.
2. Then, we call this Widget through the R Method in the template (the W method is used in the template for the extended Widget method). If you do not know about the R function, refer to here. http://www.thinkphp1.cn/info/134.html)
{: R ('cate/Menu ', '', 'widget ')}
The output result after execution is: menuWidget
3. If the menu method of the CateWidget class is changed:
The Code is as follows:
Class CateWidget extends Action {
Public function menu (){
Echo 'menuwidget ';
}
}
4. The Rules Used in the template need to be changed:
The Code is as follows:
{~ R ('cate/Menu ', '', 'widget ')}
5. If you need to use parameters when calling widgets, you can define them as follows:
The Code is as follows:
Class CateWidget extends Action {
Public function menu ($ id, $ name ){
Echo $ id. ':'. $ name;
}
}
6. Call the parameters in the template using:
The Code is as follows:
{: R ('cate/Menu ', array (5, 'thinkphp'), 'components ')}
The output is 5: thinkphp.
7. Here is a complex example:
The Code is as follows:
Class CateWidget extends Action {
Public function menu (){
$ Menu = M ('cate')-> getField ('Id, title ');
$ This-> assign ('menu ', $ menu );
$ This-> display ('cate: menu ');
}
}
8. The catewiet class renders a template file Tpl/Cate/menu.html. The flexibility of calling templates is also the difference in using this method to implement widgets (the renderFile method must be called in the Widget Extension Method to render the template ).
Usage in the menu.html template file: {$ key }:{ $ title}
I hope this article will help you with ThinkPHP framework programming.