php实现模板
PHP 实现模板的方法
PHP 实现模板通常是为了将业务逻辑与展示层分离,提高代码的可维护性和可读性。以下是几种常见的 PHP 模板实现方法:
原生 PHP 模板
直接使用 PHP 原生语法作为模板语言,简单易用,无需额外依赖。
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<h1><?php echo $heading; ?></h1>
<p><?php echo $content; ?></p>
</body>
</html>
使用短标签
PHP 提供了短标签语法,可以进一步简化模板代码。
<!DOCTYPE html>
<html>
<head>
<title><?= $title ?></title>
</head>
<body>
<h1><?= $heading ?></h1>
<p><?= $content ?></p>
</body>
</html>
使用模板引擎
为了更清晰地将逻辑与视图分离,可以使用第三方模板引擎,如 Twig、Smarty 或 Blade。
Twig 示例
安装 Twig:
composer require twig/twig
使用 Twig 模板:
require_once 'vendor/autoload.php';
$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader);
echo $twig->render('index.twig', [
'title' => 'My Page',
'heading' => 'Welcome',
'content' => 'This is a Twig template example.'
]);
模板文件 index.twig:

<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ heading }}</h1>
<p>{{ content }}</p>
</body>
</html>
Smarty 示例
安装 Smarty:
composer require smarty/smarty
使用 Smarty 模板:
require_once 'vendor/autoload.php';
$smarty = new Smarty();
$smarty->setTemplateDir('templates');
$smarty->assign('title', 'My Page');
$smarty->assign('heading', 'Welcome');
$smarty->assign('content', 'This is a Smarty template example.');
$smarty->display('index.tpl');
模板文件 index.tpl:
<!DOCTYPE html>
<html>
<head>
<title>{$title}</title>
</head>
<body>
<h1>{$heading}</h1>
<p>{$content}</p>
</body>
</html>
自定义模板引擎
如果需要更灵活的解决方案,可以自定义一个简单的模板引擎。

class SimpleTemplate {
private $templateDir;
public function __construct($templateDir) {
$this->templateDir = $templateDir;
}
public function render($template, $data = []) {
extract($data);
ob_start();
include $this->templateDir . '/' . $template . '.php';
return ob_get_clean();
}
}
$template = new SimpleTemplate('templates');
echo $template->render('index', [
'title' => 'My Page',
'heading' => 'Welcome',
'content' => 'This is a custom template example.'
]);
模板文件 templates/index.php:
<!DOCTYPE html>
<html>
<head>
<title><?= $title ?></title>
</head>
<body>
<h1><?= $heading ?></h1>
<p><?= $content ?></p>
</body>
</html>
使用 Blade 模板引擎
Laravel 的 Blade 模板引擎也可以独立使用。
安装 Blade:
composer require duncan3dc/blade
使用 Blade 模板:
require_once 'vendor/autoload.php';
$views = __DIR__ . '/views';
$cache = __DIR__ . '/cache';
$blade = new \Duncan3dc\Blade\Blade($views, $cache);
echo $blade->make('index', [
'title' => 'My Page',
'heading' => 'Welcome',
'content' => 'This is a Blade template example.'
])->render();
模板文件 views/index.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>{{ $title }}</title>
</head>
<body>
<h1>{{ $heading }}</h1>
<p>{{ $content }}</p>
</body>
</html>
总结
PHP 实现模板的方法多种多样,从原生语法到第三方模板引擎,可以根据项目需求选择合适的方案。原生语法适合简单项目,而 Twig、Smarty 或 Blade 等模板引擎更适合需要严格分离逻辑与视图的复杂项目。自定义模板引擎则提供了更高的灵活性。





