四、模版组合
在页面设计中,常用的最佳实践是把一个复杂的页面划分为不同的部分,同样模版文件中也应该指定不同的部分,最后再将其组合起来,比如下图是常件的模版件结构:
可以看到有头部,尾部和页面的主体三部分组成,下面给出它们的模版文件header.tpl:
- <!-- BEGIN header.tpl -->
- <html>
- <head></head>
- <body>
- <table width="100%" border="1">
- <tr>
- <td align="center"><a href="#">Home</a></td>
- <td align="center"><a href="#">News</a></td>
- <td align="center"><a href="#">Weather</a></td>
- <td align="center"><a href="#">Hotels</a></td>
- <td align="center"><a href="#">Dining</a></td>
- </tr>
- </table>
- <p />
- <h2>{$title}</h2>
- <p />
- <!-- END header.tpl -->
- footer.tpl
- <!-- BEGIN footer -->
- <table width="100%" align="center">
- <tr>
- <td align="center"><font size="-2">© {$year}. All rights reserved.</font></td>
- </tr>
- </table>
- </body>
- </html>
而Dwoo中,使用include可以将不同的模版包含到同一个模版中去,比如下面是框架主模版文件main.tpl:
- {include(file='header.tpl')}
- <!-- BEGIN main.tpl -->
- <table border="1">
- <tr>
- <td valign="top">
- <strong>{$headline}</strong>
- <p />
- {$content}
- </td>
- <td valign="top" align="center" width="25%">
- <strong>Special Feature</strong><br />
- {$feature}
- </td>
- </tr>
- </table>
- <!-- END main.tpl -->
- {include(file='footer.tpl')}
而框架文件的php文件如下,可以为主框架模版中的变量赋值:
- <?php
- include 'dwooAutoload.php';
- try {
- $dwoo = new Dwoo();
- $tpl = new Dwoo_Template_File('tmpl/main.tpl');
- $data = new Dwoo_Data();
- $data->assign('title', 'Welcome to London!');
- $data->assign('headline', 'Playing in the Park');
- $data->assign('content', 'It\'s a warm summer day, and Simon finds the lake in St. James Park too inviting for words...');
- $data->assign('feature', 'Tower Bridge - Snapshots from the Top');
- $data->assign('year', date('Y', mktime()));
- $dwoo->output($tpl, $data);
- } catch (Exception $e) {
- echo "Error: " . $e->getMessage();
- }
- ?>
可以得出如下结果:
而另外的实现方法,是不使用include,而是在主框架模版中如下设置:
- {$header}
- <!-- BEGIN main.tpl -->
- <table border="1">
- <tr>
- <td valign="top">
- <strong>{$headline}</strong>
- <p />
- {$content}
- </td>
- <td valign="top" align="center" width="25%">
- <strong>Special Feature</strong><br />
- {$feature}
- </td>
- </tr>
- </table>
- <!-- END main.tpl -->
- {$footer}
而在PHP文件中,再动态设置header和footer的变量的值,
- $data->assign('header',$dwoo->get(new Dwoo_Template_File('tmpl/header.tpl'), $data));
- $data->assign('footer',$dwoo->get(new Dwoo_Template_File('tmpl/footer.tpl'), $data));
这里使用了Dwoo中的get方法,将两个模版文件中的内容提取出来,设置到header和footer两个变量中去。
PHP之友评论