smarty生成静态页面的方法

WBOY
发布: 2016-07-25 09:10:32
原创
902 人浏览过
示例代码: require('libs/Smarty.class.php'); $tpl=new Smarty(); $tpl->template_dir='./templates/'; $tpl->compile_dir='./templates_c'; $tpl->config_di

示例代码: require('libs/Smarty.class.php'); $tpl=new Smarty(); $tpl->template_dir='./templates/'; $tpl->compile_dir='./templates_c'; $tpl->config_dir='./config/'; $tpl->cache_dir='./cache/'; $tpl->left_delimiter='right_delimiter='}>'; ob_start(); //打开输出缓冲区

$tpl->assign('s_title',$_POST['title']);//设置网站标题 //以下为接受传递过来的变量并赋值到模板页 $tpl->assign("title",$_POST['title']); $tpl->assign("content",stripslashes($_POST['content'])); $tpl->assign("time",date("Y-m-d")); $tpl->display("tpl.html"); $this_my_f=ob_get_contents();//读取缓冲区数据 ob_end_clean();//清空缓冲区数据 //------------------------创建文件夹--------------------------- $dir_name =date("Ymd"); //以当前日期,创建应该生成的静态页面所要存入的目录 if (!is_dir("webpage/".$dir_name)) //先判断是否已经创建了此目录!无,则先创建此目录 { mkdir("webpage/".$dir_name); } $filename ="tpl.html"; //-------------------------静态页保存的路径-------------------- if(tohtmlfile_cjjer($filename,$this_my_f)){ echo ("生成页面成功"); }else{ echo ("") } ?> function tohtmlfile_cjjer($file_cjjer_name,$file_cjjer_content) { //$dir_name =date("Ymd"); //以当前日期,创建应该生成的静态页面所要存入的目录 //if (!is_dir($dir_name)) //先判断是否已经创建了此目录!无,则先创建此目录 //{ //mkdir($dir_name); //}

if (is_file ($file_cjjer_name)){ @unlink ($file_cjjer_name); } $cjjer_handle = fopen ($file_cjjer_name,"w"); if (!is_writable ($file_cjjer_name)){ return false; } if (!fwrite ($cjjer_handle,$file_cjjer_content)){ return false; } fclose ($cjjer_handle); //关闭指针 return $file_cjjer_name; } Smarty最大的功能是做模版的页面缓存。也就是通过Smarty可以完成两个步骤:编译+解析 第一步:编译。是指把模版文件的标签替换为纯php,再保存在缓存位置,保存的文件扩展名是PHP,我把这个步骤叫做编译(这是我自己的叫法,不是官方的) 第二步:解析。也就是把刚才编译的PHP文件解析执行而已~~这个就不用多做解释了 切入正题,在Smarty.class.php文件中加入如下代码 function MakeHtmlFile($file_name, $content) { //目录不存在就创建 if (!file_exists (dirname($file_name))) { if (!@mkdir (dirname($file_name), 0777)) { die($file_name."目录创建失败!"); } } if(!$fp = fopen($file_name, "w")){ echo "文件打开失败!"; return false; }

if(!fwrite($fp, $content)){ echo "文件写入失败!"; fclose($fp); return false; } fclose($fp); chmod($file_name,0666); } 这个函数的作用就是保存文件~~

调用方法如下 require '../libs/Smarty.class.php'; $smarty = new Smarty; //…………省略变量定义和赋值 //$smarty->display('index.tpl'); $content=$smarty->fetch("index.tpl"); $smarty->MakeHtmlFile('./index.html',$content);//生成

smarty生成静态页面总结: 生成静态页面时分离模板的一个方法 通常的做法是:读取模板,用正则表达式等将模板中的变量替换成我们想要的值才能生成静态页面。经高手指点原来SMARTY就有这功能,研究了一下果然很方便,用起来也很简单,要点如下: ob_start();//开启缓冲区 $smarty->assign(“a”,$a); $smarty->display(”temp.html”); $html_content= ob_get_contents(); //读取缓冲区的数据 ob_end_clean();//关闭缓冲区 $htm_content里头的东西就是想要的东西了,将它写入页面就可以了。



来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!