阅读量:79
在PHP中实现模板渲染可以使用各种方式,下面列举了一种比较常用的方法:
- 创建一个模板文件,如template.php,里面包含所需的HTML和PHP代码,例如:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $pageTitle; ?></title>
</head>
<body>
<h1><?php echo $heading; ?></h1>
<p><?php echo $content; ?></p>
</body>
</html>
- 在PHP文件中定义变量并包含模板文件,例如:
<?php
$pageTitle = "Welcome to My Website";
$heading = "Hello World!";
$content = "This is some sample content.";
// Include the template file
include 'template.php';
?>
- 当PHP文件被访问时,模板文件中的PHP代码将会被执行,并输出最终的HTML内容。
这种方法简单易懂,适用于小型项目。对于大型项目,可以考虑使用模板引擎,如Twig、Smarty等,提供更多的功能和灵活性。