Smarty模板引擎之简单入门应用

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

一、开始使用Smartycss

 

  
  
           
  
  
  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怎么写,以下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文件就能够了。你们能够本身尝试写一下,会加深理解的。ide

相关文章
相关标签/搜索