smarty简单介绍
示意图如下
简单介绍smarty.class.php类的大体内容,如下:
<?php class Smarty //此类就是libs中的Smarty.class.php类 { public $leftlimit="<{"; //左分隔符 public $rightlimit="}>";//右分隔符 public $attr; //存放变量信息的数组 //注册变量 function assign($k,$v) { $this->attr[$k] = $v; //向数组中添加一个值,相当于$sttr[0]="sdc123" } //显示模板 function display($name) { //1.造模板路径 $filename = $mubanlujing.$name; //2.获取模板内容,内容是一大串代码,(例如模板为index.html) $str=file_get_contents($filename); /*$str里面的代吗内容 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <div>{$aa}</div> </body> </html> */ //3.用正则去匹配字符串中出现的{}里面的内容 //4.将内容读取(读取到的是数组里面的key),拿key去数组attr里面取value值 /*$str里面的代码内容 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <div><?php echo $attr[key]?></div> </body> </html> */ //5.将str里面的内容保存在缓存文件里面 file_put_contents($filename,$str);//$filename是新的文件 //6.将存储的文件加载到当前页面 include(filename); } }
配置文件:
<?php define("ROOT",str_replace("\","/",dirname(__FILE__)).'/'); //常量ROOT中指定项目根目录,方便我们定义文件夹或缓存文件 //echo str_replace("\","/",dirname(__FILE__))."/"; //dirname(__FILE__))代表当前文件的目录c:wampwww 603 require ROOT.'libs/Smarty.class.php'; //加载Smarty类文件 $smarty = new Smarty(); //实例化Smarty对象<br> //$smarty -> auto_literal = false; //就可以让定界符号使用空格 $smarty->setTemplateDir(ROOT.'templates/'); //设置所有模板文件存放位置 //$smarty->addTemplateDir(ROOT.'templates2/'); //添加一个模板文件夹 $smarty->setCompileDir(ROOT.'templates_c/'); //设置编译过的模板存放的目录 $smarty->addPluginsDir(ROOT.'plugins/'); //设置为模板扩充插件存放目录 $smarty->setCacheDir(ROOT.'cache/'); //设置缓存文件存放目录 $smarty->setConfigDir(ROOT.'configs/'); //设置模板配置文件存放目录 $smarty->caching = false; //设置Smarty缓存开关功能 $smarty->cache_lifetime = 60*60*24; //设置缓存模板有效时间一天 $smarty->left_delimiter = '<{'; //设置模板语言中的左结束符 $smarty->right_delimiter = '}>'; //设置模板语言中的右结束符
第一个smarty简单示例
1.后端服务器代码main.php
<?php //引入配置文件 include("../init.inc.php"); $name="张三"; $age=15; $attr=array("淄博","张店");//索引数组 $attrl=array("han"=>"汉族","man"=>"满族");//关联数组 class Ren //类 { public $name="王五"; } $r=new Ren(); $smarty->assign("name",$name);//注册变量 $smarty->assign("age",$age); $smarty->assign("dizhi",$attr); $smarty->assign("minzu",$attrl); $smarty->assign("ren",$r); $smarty->display("main.html");//显示模板
2.前端网页代码main.html
<html> <head> <meta charset="utf-8"/> </head> <body> <h1>这是主页面</h1> <div style="color:#F39">登陆者:<{$name}></div> <div>年龄:<{$age}></div> <div>地址:<{$dizhi[0]}></div> <div>民族:<{$minzu["han"]}></div> <div>民族:<{$minzu.man}></div> <div>好友:<{$ren->name}></div> </body> </html>