这篇文章介绍了PHP用Smarty 4.3怎么生成静态页面。

PHP利用Smarty 4.3生成静态页面HTML
PHP利用Smarty 4.3生成静态页面HTML

一、下载Smarty 4.3

Smarty的下载地址:Smarty

作者已经把文件放到了百度网盘,也可以到百度网盘分享下载:

链接:https://pan.baidu.com/s/1QhHcj8RQ17cx69vuGM4jkg?pwd=wing
提取码:wing

二、使用

1.  解压后有多个文件,我们只需要libs这个文件夹。

根据需要改名,引用代码就可以使用

require_once'smarty-4.3.4/Smarty.class.php';

2. 创建模板文件

模板文件,如:index.tpl,后缀名一般是tpl,也可以是其它,比如通用的html.
<!DOCTYPE html>
<html lang="en">


<head>
    <meta charset="UTF-8">
    <title>{$title}</title>
</head>


<body>
    <div>
        <h1>{$content}</h1>
        <ul>
            {foreach $items as $item}
            <li>{$item}</li>
            {foreachelse}
            <li>No items found</li>
            {/foreach}
        </ul>
        {if $showFooter}
        <footer>
            Copyright © 2021
        </footer>
        {/if}
    </div>
</body>


</html>

3. PHP 成静态页面代码

<?php
require_once 'smarty-4.3.4/Smarty.class.php';
$tem_path = $_SERVER['DOCUMENT_ROOT'] . '/templates'; //模板目录
$html_path = $_SERVER['DOCUMENT_ROOT'] . '/pr/'; //生成页面目录
if (!is_dir($html_path)) {
    mkdir($html_path); // echo "文件夹已创建。";
}
$i = 0;
while ($i < 101) {
    $smarty = new Smarty;
    $smarty->setTemplateDir($tem_path); // 设置模板目录
  // $smarty->setCompileDir($compile_path); // 设置编译目录
   // $smarty->setCacheDir($cache_path); // 设置缓存目录
   // $smarty->setConfigDir($config_path); // 设置配置目录
  //  $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); // 设置缓存时间
    $smarty->assign("title", "标题" . $i);
    $smarty->assign("content", "内容" . $i);
    $contect = $smarty->fetch("tpl1.html");
    $fp = fopen($html_path . "index_$i.html", "w");
    fwrite($fp, $contect);
    fclose($fp);
    echo "生成页面index_$i.html<br/>";
    $i++;
}
运行页面
生成了需要的页面
 静态页面代码
<!DOCTYPEhtml>
<htmllang="en">


<head>
<metacharset="UTF-8">
<title>标题0</title>
</head>


<body>
<div>
<h1>内容0</h1>
<ul>
<li>No items found</li>
</ul>
</div>
</body>


</html>

总结

PHP利用Smarty 4.3生成静态页面HTML,简单快捷。