昨晚回来后,就去看了一下Smarty模板引擎的使用,感觉其实对于新手来说应该还是很好用的。也很容易懂。因为之前学过ThinkPHP,所以,理解起来也不难,应用起来也挺好的,不过,这种东西,也还是要多在项目中使用才会越顺手。

1、开始使用Smarty

 

 
  1. /*  
  2. *index.php  
  3. *author:qtvb-star  
  4. */ 
  5.  
  6. require "Smarty.class.php"//加载Smarty引擎,这是核心文件  
  7. $smarty = new Smarty();//实例化  
  8. $smarty -> template_dir = './templates/';//模板目录  
  9. $smarty -> compile_dir  = './templates_c/';//编译目录  
  10. $smarty -> config_dir   = './configs/';//配置目录,刚开始用可能不会用,后期可能会用上  
  11. $smarty -> cache_dir    = './cache/';//缓存目录  
  12. $smarty -> assign('name''my name');//给变量赋值  
  13. $smarty -> display('index.tpl');//显示模板,也可以是index.html这种文件  

然后这就是最简单的使用了,关于index.tpl或者index.html怎么写,如下

 

 
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
  3. <head> 
  4.     <title>{$name}</title> 
  5. <style type="text/css"> 
  6. {literal}  
  7. {/literal}  
  8. </style> 
  9. </head> 
  10. <body> 
  11. {$dc}  
  12. <h1>{$name}会显示在这里</h1> 
  13.  
  14. </body> 
  15. </html> 

默认的单词分割符是“{”与“}”,这个是可以自己修改,具体不介绍。

其实之前我也不懂这个原理的,后来,自己百度了下,如何自己写模板引擎,然后明白了,原理差不多都是一样的,就是用正则匹配{}这个定义的分割符,然后,替换成<?php echo $name ?>这种形式,当然,其它循环语句也类似。然后把替换后的内容写进一个php文件,然后在index.php中include那个php文件就可以了。大家可以自己尝试写一下,会加深理解的。