smarty模板基础知识

1、定义

         Smarty是一个使用php写出来的模板引擎,它分离了逻辑代码和外在的内容,提供了一种易于管理和使用的方法,用来将原本与html代码混杂在一起PHP代码逻辑分离。

简单的讲,目的就是要使PHP程序员同前端人员分离,使程序员改变程序的逻辑内容不会影响到前端人员的页面设计,前端人员重新修改页面不会影响到程序的程序逻辑,这在多人合作的项目中显的尤为重要。

2、

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
     class Smarty
     {
         public $left = "{" //左分割符
         public $right = "}" ;
         
         
         //所有后台数据要存在这个数组里;
         public $arr = array ();
         
         
         //注册变量(将这个变量写到数组里存一下),将得到的数据传到上面的数组中
         public function assign( $name , $value ){
             $arr [ $name ] = $value ;
         }
         
         
         //显示模板(核心)(看下图)
         public function display( $url ){
             
             //找到模板文件
             $str = file_get_contents ( $url );
             
             //根据正则匹配带有标记({})的内容,做替换
         
             //将编译好的文件缓存下来          
             file_get_contents ( "" , $str );
         
             //将文件拿到当前页面显示
             include ();
 
         }
     
     }
     
     
 
 
?>

  

 

 

 

 

 

3、例子:

(1)在12.php页面:(字符串类型;数组;对象)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
     //引入smarty类
require "../init.inc.php" ;
 
//数组类型
$arr = array ( "one" => "1111" , "two" => "2222" );
 
//对象
class Ren{
     public $name = "张三" ;
}
$r = new Ren();
 
//注册变量
$smarty ->assign( "ceshi" , "hello" );  //字符串
$smarty ->assign( "shuzu" , $arr );  //数组
$smarty ->assign( "duixiang" , $r );  //对象
 
//显示
$smarty ->display( "test.html" );
?>

  (2)test.html页面

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns= "http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
 
<body>
<{ $ceshi }>
<{ $shuzu [ "one" ]}>
<{ $duixiang ->name}>
</body>
</html>

  (3)运行12.php,结果如下:

转载于:https://www.cnblogs.com/Liangbingbing/p/7153829.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值