使用 php 函数显示 html

Using php functions to display html

我正在做一个小项目,我想在不使用任何模板引擎的情况下应用某种模板来显示包含在每个页面上的主模板文件之间的内容。目前我有以下页面。

layout.template.php

<!DOCTYPE html>
<html lang="en">
<head>

</head>
<body>
  <!-- page content displays here -->
  <?php show_content(); ?>
</body>
</html>

index.php

<?php function show_content(){ ?>
<div>
    <h1>Home page</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<?php } 
include 'layout.template.php';
?>

second.php

<?php function show_content(){ ?>
<div>
    <h1>Second page</h1>
    <p>some other content</p>
</div>
<?php }
include 'layout.template.php';
?>

我使用 show_content() 函数来定义将呈现到每个页面上的 layout.template.php 文件中的 html。当包含 layout.template.php 时,它会调用该函数并根据包含它的页面在其中显示 html 代码。我的问题是

这是个好主意还是做法? 我有什么替代方法可以实现这一目标(除了使用模板引擎)?

没有一个完美的答案,因为有太多方法可以做到。

一个好的解决方案是将视图 (HTML) 与逻辑 (PHP) 分开。可能 MVC 会是一个很好的答案。

如果你只想练习:

创建一个文件夹并将所有 HTML 文件放入该文件夹。然后你有你的 PHP 文件,其中包含一个调用你想要显示的 HTML 内容的函数(或者甚至可能是一个方法)。 如果你的HTML内容还包括PHP,最好不要命名为myFile.php。在这种情况下,称它为 myFile.phtml,以便您清楚,它是 HTML,但它的一部分也是 PHP。