php实现模板
PHP实现模板的方法
使用原生PHP模板
原生PHP可以直接嵌入HTML中作为模板使用。创建一个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>
变量可以在包含模板前定义:
$title = "首页";
$heading = "欢迎";
$content = "这是一个PHP模板示例";
include 'template.php';
使用模板引擎
第三方模板引擎如Smarty、Twig或Blade提供更强大的功能。
Smarty示例 安装Smarty后:
require 'smarty/libs/Smarty.class.php';
$smarty = new Smarty;
$smarty->assign('title', '首页');
$smarty->assign('heading', '欢迎');
$smarty->assign('content', 'Smarty模板示例');
$smarty->display('template.tpl');
模板文件template.tpl:

<!DOCTYPE html>
<html>
<head>
<title>{$title}</title>
</head>
<body>
<h1>{$heading}</h1>
<p>{$content}</p>
</body>
</html>
使用短标签语法
PHP支持短标签语法简化模板代码,需确保short_open_tag启用。
<?=$title?>
分离逻辑与表现
将业务逻辑与模板分离,提高可维护性。
逻辑文件index.php

$data = [
'title' => '分离示例',
'items' => ['苹果', '香蕉', '橙子']
];
include 'view.php';
模板文件view.php
<!DOCTYPE html>
<html>
<head>
<title><?=htmlspecialchars($data['title'])?></title>
</head>
<body>
<ul>
<?php foreach ($data['items'] as $item): ?>
<li><?=htmlspecialchars($item)?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
使用输出缓冲
通过输出缓冲控制模板渲染时机。
ob_start();
include 'template.php';
$output = ob_get_clean();
echo $output;
模板继承
高级模板引擎支持继承机制,如Twig:
{% extends "base.html" %}
{% block content %}
<h1>{{ heading }}</h1>
<p>{{ content }}</p>
{% endblock %}
基础模板base.html:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
每种方法适用于不同场景,原生PHP适合简单项目,模板引擎适合需要复杂功能的大型应用。






