php实现模板
PHP 实现模板的方法
使用原生 PHP 作为模板引擎
PHP 本身可以作为模板引擎使用,通过混合 HTML 和 PHP 代码实现动态内容渲染。
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<h1><?php echo $heading; ?></h1>
<p><?php echo $content; ?></p>
</body>
</html>
使用 include 或 require 分离布局
将重复的部分(如页眉、页脚)分离到单独的文件中,通过 include 引入。
// header.php
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
// footer.php
</body>
</html>
// index.php
<?php
$title = "首页";
include 'header.php';
?>
<h1>欢迎</h1>
<?php include 'footer.php'; ?>
使用 HEREDOC 语法生成模板
对于较复杂的模板,可以使用 HEREDOC 语法保持格式。

$template = <<<EOT
<div class="post">
<h2>{$post['title']}</h2>
<div class="content">
{$post['content']}
</div>
</div>
EOT;
echo $template;
使用第三方模板引擎
对于更复杂的需求,可以使用专门的模板引擎如 Twig、Smarty 或 Blade。
Twig 示例
// 安装 Twig
composer require twig/twig
// 使用示例
require_once 'vendor/autoload.php';
$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader);
echo $twig->render('index.twig', [
'name' => '张三',
'items' => ['苹果', '香蕉', '橙子']
]);
Smarty 示例
// 安装 Smarty
composer require smarty/smarty
// 使用示例
require_once 'vendor/autoload.php';
$smarty = new Smarty();
$smarty->assign('title', 'Smarty 示例');
$smarty->assign('content', '这是使用 Smarty 的内容');
$smarty->display('template.tpl');
模板继承实现布局
现代模板引擎通常支持布局继承,可以创建基础模板然后扩展。

Twig 继承示例
{# base.twig #}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
{# page.twig #}
{% extends "base.twig" %}
{% block title %}我的页面{% endblock %}
{% block content %}
<h1>欢迎</h1>
<p>这是页面内容</p>
{% endblock %}
自定义简单模板引擎
可以创建简单的模板解析函数来处理自定义模板语法。
function renderTemplate($file, $data) {
if (!file_exists($file)) {
return "模板文件不存在";
}
$content = file_get_contents($file);
foreach ($data as $key => $value) {
$content = str_replace("{{" . $key . "}}", $value, $content);
}
return $content;
}
// 使用示例
echo renderTemplate('template.html', [
'title' => '自定义模板',
'content' => '这是通过自定义函数渲染的内容'
]);
安全注意事项
在实现模板时需要注意安全性,特别是当允许用户提供模板内容时:
- 对输出进行转义:使用
htmlspecialchars()防止 XSS 攻击 - 限制模板文件访问:确保模板文件不能直接被访问
- 验证模板内容:如果允许用户上传模板,需要严格验证内容
// 安全输出示例
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');






