php使用smarty实例

1、下载smarty将解压后的libs目录copy到项目目录下。

2、新建一个php文件,假如和libs目录同一级上。命名为smarty_test.php,然后增加两个目录一个为Templates文件夹,另一个为Templates_c目录,前者是以后模板文件要存放的目录,后者是smary编译后的文件存放目录。

3、在Templates目录下建立一个template.htm文件,输入以下代码:

1 <html>

2 <head>

3 <style type="text/css">

4 .bold{

5 font-weight:bold;

6 font-size:12px;

7 padding:10px;

8 width: 300px;

9 border:solid 1px blue;

10 line-height:20px;

11 }

12 </style>

13 </head>

14 <body>

15 <div class="bold">{{$test}}</div>

16 </body>

17 </html>

3、在smart_test.php中输入以下代码

1 <?php

2 include_once('./libs/Smarty.class.php'); //如果在php.ini文件中将include_path添加了smart的目录这里就直接写Smarty.class.php就可以了。

3

4 $smarty = new Smarty();

5 $smarty -> template_dir = "./Templates"; //模板存放目录

6 $smarty -> compile_dir = "./Templates_c"; //编译目录

7 $smarty -> left_delimiter = "{{"; //左定界符

8 $smarty -> right_delimiter = "}}"; //右定界符

9 $smarty -> assign('test','if success display this contents.');

10 $smarty -> display('template.htm');

11 ?>

保存,浏览smart_test.php会发现在htm文件中的{{test}}被替换成了“if success display this contents.“。