background image

3.

 

实现一个简单的例子

( 1 ) 在 /var/www/yqting/ 下 创 建 目 录 weibo/ , 然 后 在 weibo/ 目 录 下 创 建 cache/ 、 
configs/、templates/和 templates_c/目录,修改 cache/和 templates_c/目录的权限为可读写。

 

(2)新建一个模板文件:index.tpl,将此文件放在/var/www/yqting/weibo/templates 目录下,

 

代码如下:
  <html> 
  <head> 
  <metahttp-equiv="Content-Type" content="text/html;charset=gb2312">
  <title>Smarty</title> 
  </head> 
  <body>
  username:{$Name}
  </body> 
  </html>  这段代码很简单,有什么不明白的继续往下看,不要着急!每一个做显
示的.tpl 文件都会对应一个处理业务逻辑的.php 文件,下面介绍这个.php 文件。
(3)新建 index.php,将此文件放在/var/www/yqting/weibo/

 

下,代码如下:

  <?php   /*sample example */  require '../libs/Smarty.class.php';   $smarty = new 
Smarty();   $username = "Smarty";   $smarty->assign("Name",$username);   $smarty-
>display('index.tpl');   ?>   其中 require 使用的路径一定要正确,可以参照上面的目
录结构看一下!
(4)在 Smarty3 中,Smarty 类的构造函数中已经指定了 template_dir、compile_dir 、
config_dir 和 cache_dir

 

 

,不需要再次指定。     

(5

 

) 在浏览器中输入 http://localhost/yqting/weibo/index.php,就可以看到输出的信息

username:Smarty 

 

了。

二、解释 smarty

 

的程序

  我们可以看到,smarty 的程序部分实际就是符合 php 语言规范的一组代码,我们依

 

次来解释一下:   
(1)/**/语句:
  包含的部分为程序篇头注释。主要的内容应该为对程序的作用,版权与作者及编写时

 

间 做一个简单的介绍,这在 smarty 中不是必需的,但从程序的风格来讲,这是一个好的

 

风格。   
(2)include_once 语句:
  它将安装到网站的 smarty 文件包含到当前文件中,注意包含的路径一定要写正确。 
(3)$smarty = new Smarty(): 
  这一句新建一个 Smarty 对象$smarty,

 

简单的一个对象的实例化。   

(4)$smarty->templates="": 
  这一句指明$smarty 对象使用 tpl 模板时的路径,它是一个目录,在没有这一句时, 
Smarty 默认的模板路径为当前目录的 templates

 

目录,实际在写程序时,我们要将这一 句

 

写明,这也是一种好的程序风格。   
(5)$smarty->templates_c="": 
  这一句指明$smarty 对象进行编译时的目录。在模板设计篇我们已经知道 Smarty

 

是 一

种编译型模板语言,而这个目录,就是它编译模板的目录,要注意,如果站点位于 linux