我目前正在建立一个静态的PHP网站。我想要的是:有一个main.php文件,它包含页面的所有公共部分(页眉、页脚、导航等等)和几个页面,比如index.php、team.php、contact.php等等。我确实希望能够以这种方式编辑main.php,也就是影响我的项目中的所有页面。但是,我确实希望能够通过直接在特定文件中编写代码(不是main.php,而是index.php)为每个页面输出一些特定的内容。因此,我希望分配项目的每个页面使用main.php作为核心模板。到目前为止,我的main.php文件如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Static Site Genarator</title>
</head>
<body>
<div id="navigation">
<?php echo navigation()?>
</div>
<div id="pageWrap">
<header>
Header
</header>
<main id="content">
<?php echo $templateContent; ?>
</main>
<footer>
Footer
</footer>
</div>
</body>
</html>还有几个页面,比如index.php,contact.php等等。他们都是这样的:
<?php include_once $_SERVER['DOCUMENT_ROOT'].'/essentials/settings.php'; ?>
<h1>
This is the h1 for the index page
</h1>
<?php require($_SERVER['DOCUMENT_ROOT'].'/essentials/exit.php'); ?>我在我的settings.php文件和我的exit.php文件中传递了一些设置,我有以下代码:
<?php
$templateContent = ob_get_contents();
ob_end_clean();
echo $templateContent;
?>在输出main.php变量时,我需要以某种方式将所有页面绑定为$templateContent的一部分
对我来说,实现这个目标的正确方法是什么?
发布于 2020-12-11 13:53:12
我个人会考虑使用像内腔、纤细、无脂骨架这样的微型PHP框架来制作哪怕是最小的PHP应用程序。
尽管如此,下面是解决问题的方法。我将保持类似于您的文件结构和文件命名,尽管这里有一个改进的地方。
让我们考虑以下应用程序结构:
essentials/main.php
essentials/navigation.php
essentials/exit.php
essentials/settings.php
index.php
about.php
contact.php如您所见,我已将所有常见文件移动到essentials文件夹中,并将所有页留在root文件夹中。
essentials/settings.php
<?php
// start output buffering
ob_start();essentials/navigation.php
<ul>
<li><a href="index.php">index</a></li>
<li><a href="contact.php">contact</a></li>
<li><a href="about.php">about us</a></li>
</ul>main.php
<?php $templateContent = ob_get_clean(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Static Site Generator</title>
</head>
<body>
<div id="navigation">
<?php include("navigation.php"); ?>
</div>
<div id="pageWrap">
<header>
Header
</header>
<main id="content">
<?= $templateContent; ?>
</main>
<footer>
Footer
</footer>
</div>
</body>
</html>
<?php require_once("exit.php"); ?>essentials/exit.php
<?php
ob_end_flush();实际页面结构index.php、about.php和contact.php看起来类似:
index.php
<?php require_once("./essentials/settings.php"); ?>
<h1>
This is the h1 for the index page
</h1>
<?php require_once("./essentials/main.php"); ?>我希望这有助于推进您的想法,但强烈鼓励您研究时间并学习一种用于PHP应用程序开发的现代方法。拉勒维尔是一个很好的陈述点。
发布于 2020-12-01 16:13:58
也许你想要这样的东西?
结构
index.php
about.php
core\function.php
core\setting.php
templates\header.php
templates\footer.php
templates\menu.phpindex.php
<?php
include_once("core\setting.php");
include_once("core\function.php");
/*
* code php for this file in here
*/
$message = 'index data';
include_once("core\header.php");
include_once("core\menu.php");
echo <<<HTML
<div>show content {$message}</div>
HTML;
include_once("core\footer.php");
?>https://stackoverflow.com/questions/65093974
复制相似问题