我建议您将 HTML 和 PHP 分开。如果您不想使用模板系统,为什么不这样做呢?
制作一个 HTML 模板:
<div id="wrapper">
<div id="leftsidebar">{LEFT}</div>
<div id="centercontent">{CONTENT}</div>
<div id="rightsidebar">{RIGHT}</div>
</div>
在不同的 php 文件中:
$content = file_get_contents('template.html');
$templateVars = array();
startVar('CONTENT');
echo '<p>This is the content.</p>'; // New template vars are also allowed
endVar('CONTENT');
echo replaceTemplateVars($content);
/**
* Replace template variables recursively with the key-value pairs that are in the $templateVars queue
* @param string $content (default NULL) is code to convert.
* @return the string that is replaced
*/
function replaceTemplateVars($content = NULL)
{
global $templateVars;
$matches = array();
preg_match_all("/{[A-Z0-9_:]*}/", $content, $matches); // $matches = All vars found in your template
foreach($matches[0] as $key)
{
if(isset($templateVars[substr($key, 1, -1)]))
{
$content = str_replace($key, $templateVars[substr($key, 1, -1)], $content); // Substitute template var with contents
}
else
{
$content = str_replace($key, "", $content); // Remove empty template var from template
}
}
// Check if the replacement has entered any new template variables, if so go recursive and replace these too
if(preg_match_all("/{[A-Z0-9_:]*}/", $content, $matches))
{
$content = replaceTemplateVars($content);
}
return $content;
}
/**
* Start output buffer for a template key
* @param string $key is not used. Only for overview purposes
*/
function startVar($key)
{
ob_start();
}
/**
* End output buffer for a template key and store the contents of the output buffer in the template key
* @param string $key
*/
function endVar($key)
{
setVar($key, ob_get_contents());
ob_end_clean();
}
/**
* @param string $key to store value in
* @param mixed $value to be stored
*/
function setVar($key, $value)
{
global $templateVars;
$templateVars[$key] = $value;
}
这就是您在屏幕上看到的内容:
<div id="wrapper">
<div id="leftsidebar"></div>
<div id="centercontent"><p>This is the content.</p></div>
<div id="rightsidebar"></div>
</div>
所以先做预处理,最后输出所有的html代码。
当然,您可以添加和之类的函数startPrependVar()
并将startAppendVar()
所有内容包装到 Template 类中以摆脱全局范围。