php原生模板引擎实现
PHP原生模板引擎实现
PHP本身支持直接嵌入HTML代码,但原生模板引擎可以更好地分离逻辑与视图。以下是几种实现方式:
使用PHP原生语法
PHP原生语法已经具备模板引擎的基础功能,通过<?php ?>标签嵌入逻辑:
<!DOCTYPE html>
<html>
<head>
<title><?= htmlspecialchars($title) ?></title>
</head>
<body>
<?php foreach ($items as $item): ?>
<li><?= htmlspecialchars($item) ?></li>
<?php endforeach; ?>
</body>
</html>
自定义简单模板引擎
通过ob_start()和ob_get_clean()实现模板渲染:

function renderTemplate($templatePath, $data = []) {
extract($data);
ob_start();
include $templatePath;
return ob_get_clean();
}
// 使用示例
$data = ['title' => 'Home', 'items' => ['Item 1', 'Item 2']];
echo renderTemplate('template.php', $data);
实现变量替换
通过字符串替换实现简单模板功能:
function renderTemplate($template, $data) {
foreach ($data as $key => $value) {
$template = str_replace("{{$key}}", htmlspecialchars($value), $template);
}
return $template;
}
// 使用示例
$template = '<h1>{title}</h1><p>{content}</p>';
$data = ['title' => 'Hello', 'content' => 'World'];
echo renderTemplate($template, $data);
支持条件判断和循环
扩展模板引擎以支持基本逻辑:

function renderTemplate($template, $data) {
extract($data);
ob_start();
eval('?>' . $template);
return ob_get_clean();
}
// 使用示例
$template = <<<'TPL'
<?php if ($show): ?>
<h1><?= $title ?></h1>
<?php endif; ?>
TPL;
$data = ['show' => true, 'title' => 'Dynamic Title'];
echo renderTemplate($template, $data);
模板继承
实现类似其他模板引擎的继承功能:
function extendTemplate($parent, $child) {
ob_start();
include $parent;
$parentContent = ob_get_clean();
ob_start();
include $child;
$childContent = ob_get_clean();
return str_replace('@yield', $childContent, $parentContent);
}
// parent.php
// <html><body>@yield</body></html>
// child.php
// <h1>Content</h1>
安全注意事项
使用原生PHP模板时需注意:
- 始终对输出进行转义:
htmlspecialchars() - 避免直接执行用户提供的模板代码
- 考虑使用
strip_tags()过滤HTML标签
这些方法提供了从简单到相对复杂的PHP原生模板实现方案,可根据项目需求选择合适的方式。





