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 file inclusion methods. the above is the simplest method to include operations.
Problem description:Problems encountered during Project creation are also very common. Generally, the home page contains headers and Footsteps. to facilitate management, these problems need to be implemented by using included 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:
- 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.thinkphp.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:
- Class CateWidget extends Action {
- Public function menu (){
- Echo 'menuwidget ';
- }
- }
4. The rules used in the template need to be changed:
{~ R ('Cate/Menu ', '', 'widget ')}
5. if you need to use parameters when calling widgets, you can define them as follows:
- Class CateWidget extends Action {
- Public function menu ($ id, $ name ){
- Echo $ id. ':'. $ name;
- }
- }
6. call the parameters in the template using:
{: R ('Cate/Menu ', array (5, 'thinkphp'), 'components ')}
The output is 5: thinkphp.
7. here is a complex example:
- 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}