PHP头条
热点:

四、模版组合

在页面设计中,常用的最佳实践是把一个复杂的页面划分为不同的部分,同样模版文件中也应该指定不同的部分,最后再将其组合起来,比如下图是常件的模版件结构:

mobanjianjiegou

可以看到有头部,尾部和页面的主体三部分组成,下面给出它们的模版文件header.tpl:

  1. <!-- BEGIN header.tpl --> 
  2. <html> 
  3. <head></head> 
  4. <body> 
  5. <table width="100%" border="1"> 
  6. <tr> 
  7. <td align="center"><a href="#">Home</a></td> 
  8. <td align="center"><a href="#">News</a></td> 
  9. <td align="center"><a href="#">Weather</a></td> 
  10. <td align="center"><a href="#">Hotels</a></td> 
  11. <td align="center"><a href="#">Dining</a></td> 
  12. </tr> 
  13. </table> 
  14. <p /> 
  15. <h2>{$title}</h2> 
  16. <p /> 
  17. <!-- END header.tpl --> 
  18. footer.tpl  
  19. <!-- BEGIN footer --> 
  20. <table width="100%" align="center"> 
  21. <tr> 
  22. <td align="center"><font size="-2">&copy; {$year}. All rights reserved.</font></td> 
  23. </tr> 
  24. </table> 
  25. </body> 
  26. </html> 

而Dwoo中,使用include可以将不同的模版包含到同一个模版中去,比如下面是框架主模版文件main.tpl:

  1. {include(file='header.tpl')}  
  2. <!-- BEGIN main.tpl --> 
  3. <table border="1"> 
  4. <tr> 
  5. <td valign="top"> 
  6. <strong>{$headline}</strong> 
  7. <p /> 
  8. {$content}  
  9. </td> 
  10. <td valign="top" align="center" width="25%"> 
  11. <strong>Special Feature</strong><br /> 
  12. {$feature}  
  13. </td> 
  14. </tr> 
  15. </table> 
  16. <!-- END main.tpl --> 
  17. {include(file='footer.tpl')} 

而框架文件的php文件如下,可以为主框架模版中的变量赋值:

  1. <?php  
  2. include 'dwooAutoload.php';  
  3. try {  
  4. $dwoo = new Dwoo();  
  5. $tpl = new Dwoo_Template_File('tmpl/main.tpl');  
  6. $data = new Dwoo_Data();  
  7. $data->assign('title''Welcome to London!');  
  8. $data->assign('headline''Playing in the Park');  
  9. $data->assign('content''It\'s a warm summer day, and Simon finds the lake in St. James Park too inviting for words...');  
  10. $data->assign('feature''Tower Bridge - Snapshots from the Top');  
  11. $data->assign('year'date('Y'mktime()));  
  12. $dwoo->output($tpl$data);  
  13. } catch (Exception $e) {  
  14. echo "Error: " . $e->getMessage();   
  15. }  
  16. ?> 

可以得出如下结果:

jieguo

而另外的实现方法,是不使用include,而是在主框架模版中如下设置:

  1. {$header}  
  2. <!-- BEGIN main.tpl --> 
  3. <table border="1"> 
  4. <tr> 
  5. <td valign="top"> 
  6. <strong>{$headline}</strong> 
  7. <p /> 
  8. {$content}  
  9. </td> 
  10. <td valign="top" align="center" width="25%"> 
  11. <strong>Special Feature</strong><br /> 
  12. {$feature}  
  13. </td> 
  14. </tr> 
  15. </table> 
  16. <!-- END main.tpl --> 
  17. {$footer} 

而在PHP文件中,再动态设置header和footer的变量的值,

  1. $data->assign('header',$dwoo->get(new Dwoo_Template_File('tmpl/header.tpl'), $data));  
  2. $data->assign('footer',$dwoo->get(new Dwoo_Template_File('tmpl/footer.tpl'), $data)); 

这里使用了Dwoo中的get方法,将两个模版文件中的内容提取出来,设置到header和footer两个变量中去。


www.phpzy.comtrue/php/9537.htmlTechArticle四、模版组合 在页面设计中,常用的最佳实践是把一个复杂的页面划分为不同的部分,同样模版文件中也应该指定不同的部分,最后再将其组合起来,比...

相关文章

相关频道:

PHP之友评论

今天推荐