所以我知道有很多引擎都准备好了,比如smarty,可以为我做这件事,但我想构建一个基本的引擎,只是为了我自己的学习,而不是现在就跳到别人的代码上。
到目前为止,我有一组页面(header.php、footer.php、rightPanel.php、home.php),所有这些页面都是由一个函数加载的。
<?php
require_once(realpath(dirname(__FILE__) . "/../config.php"));
function renderLayoutWithContentFile($contentFile, $variables = array())
{
$contentFileFullPath = TEMPLATES_PATH . "/" . $contentFile;
// making sure passed in variables are in scope of the template
// each key in the $variables array will become a variable
if (count($variables) > 0) {
foreach ($variables as $key => $value) {
if (strlen($key) > 0) {
${$key} = $value;
}
}
}
require_once(TEMPLATES_PATH . "/header.php");
echo "<div id='"container'">'n"
. "'t<div id='"content'">'n";
if (file_exists($contentFileFullPath)) {
require_once($contentFileFullPath);
} else {
require_once(TEMPLATES_PATH . "/error.php");
}
// close content div
echo "'t</div>'n";
require_once(TEMPLATES_PATH . "/rightPanel.php");
// close container div
echo "</div>'n";
require_once(TEMPLATES_PATH . "/footer.php");
}
?>
在index.php 中
<?php
require_once(realpath(dirname(__FILE__) . "/resources/config.php"));
require_once(LIBRARY_PATH . "/templateFunctions.php");
require_once(LIBRARY_PATH . "/dealBuilderFunctions.php");
$setInIndexDotPhp = "Hey! I was set in the index.php file.";
// Must pass in variables (as an array) to use in template
$variables = array(
'setInIndexDotPhp' => $setInIndexDotPhp,
);
renderLayoutWithContentFile("home.php", $variables);
?>
所以现在,如果我想将一组不同的内容加载到模板中,我已经想好了,我可以这样做来更改模板页面中的变量,并输入一些逻辑,让它检查是否有如下更改:
<?php
require_once(realpath(dirname(__FILE__) . "/resources/config.php"));
require_once(LIBRARY_PATH . "/templateFunctions.php");
require_once(LIBRARY_PATH . "/dealBuilderFunctions.php");
/*
Now you can handle all your php logic outside of the template
file which makes for very clean code!
*/
$setInIndexDotPhp = "Hey! I was set in the index.php file.";
// Must pass in variables (as an array) to use in template
$variables = array(
'setInIndexDotPhp' => $setInIndexDotPhp,
);
if ($page == "") {
$page = "home";
}
else {
$page=$page;
}
renderLayoutWithContentFile("$page.php", $variables);
?>
获取新页面的URL
http://siteurl.com/index.php?page=test
但我一直收到一个错误通知:Undefined variable: page in /www/sites/perthdeals/wwwroot/index.php on line 20
,我如何才能让它工作?
我认为上面应该只更改index.php中的任何变量$page
,但如果我在页面中设置它,就像错误所问的那样,我只得到我在代码中定义的页面,而不是URL中传递的页面,那么它应该如何工作呢?
或者,如果有任何现代教程可以帮助我理解这一点,我将不胜感激,谢谢。
UPDATE-Undefined variable: page in /www/sites/perthdeals/wwwroot/index.php on line 20
是在转移注意力,我试图从URL中调用错误的变量,答案标记在下面,谢谢。
URL中的参数,您可以通过$_get获得,在您的情况下是
if ($_GET["page"] == "") {
$page = "home";
}
else {
$page=$_GET["page"];
}