技术共享
技术共享 Technology sharing 当前位置:首页->技术共享->技术共享

利用smarty生成静态页的关键代码(php)

来源:截取自http://bbs.phpla.com/viewtopic.php?p=88

smarty中有一个获取模板页内容方法fetch(), 它的声明原形是这样的:

<?php

function fetch($resource_name, $cache_id = null,

  $compile_id = null, $display = false)

?>

第一个参数为模板名称, 第二个参数为缓存的id, 第三个参数为编译id, 第四个参数为是否显示模板内容. 生成静态页我们就需要用到这个方法.

<?php

   $smarty = new Smarty();

  //其它模板替换语法...

  

   //下面这句取得页面中所有内容, 注意最后一个参数为false

  $content = $smarty->fetch('模板名称.tpl', null, null, false);

  

  //下面将内容写入至一个静态文件

  $fp = fopen('news.html', 'w');

  fwrite($fp, $content);

  fclose($fp);

  //OK, 到这里这个news.html静态页就生成了, 你可以处理你下一步的工作了

?>

 

 

smarty生成静态页

 


 

<?php

require('smarty/Smarty.class.php');

$t = new Smarty;

$t->assign("title","Hello World!");

$content = $t->fetch("templates/index.htm");

//这里的 fetch() 就是获取输出内容的函数,现在$content变量里面,就是要显示的内容了

$fp = fopen("archives/2005/05/19/0001.html", "w");

fwrite($fp, $content);

fclose($fp);

?>

这个函数的作用是获取缓冲区的内容,相当于上面的那个fetch(),

道理一样的。代码:

<?php

ob_start();

echo "Hello World!";

$content = ob_get_contents();//取得php页面输出的全部内容

$fp = fopen("0001.html", "w");

fwrite($fp, $content);

fclose($fp);

?>

一个简单的smarty输出静态例子

$smarty = new Smarty;

$smarty->assign($value);

$output = $smarty->fetch("index.tpl");

//$output中就是运行的结果,但没有在页面上显示

//下面是简单的生成静态

$filename = '....';//你想存成什么就写什么

$handle = fopen($filename, 'a');

fwrite($handle, $output);

fclose($handle);

[code]

fetch

取得输出的内容

string fetch (string template [, string cache_id [, string compile_id]])

返回一个模板输出的内容(HTML代码),而不是直接显示出来,需要指定一个合法的模板资源的类型和路径。你还可以通过第二个可选参数指定一个缓存号
 

 








上一篇:Form和Input对象
下一篇:window.opener对象