我创建了一个自定义的PHP模板系统,我构建它的方式似乎很低效.我的模板的三个主要目标是:
<title>或<script>)最后,我的模板系统看起来像这样:
randomPage.php
<?php
// declare any page specific resources
$pageTitle = "Random Sub-Title";
$pageResources = "/css/someRandomCSS.css"
$pageContent = "/randomPage.tpl"
// include the generic page template
include dirname($_SERVER['DOCUMENT_ROOT']).'/includes/template.tpl'
?>
Run Code Online (Sandbox Code Playgroud)
randomPage.tpl
<h1><?=$pageTitle?></h1>
<p>Some random page's content</p>
Run Code Online (Sandbox Code Playgroud)
template.tpl
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Site -- <?=$pageTitle?></title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link href="<?=pageResources?>" rel="stylesheet" type="text/css">
</head>
<body>
<? include $pageContent ?>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这个系统的主要问题是,对于每个网页,我需要管理两个文件:一个用于逻辑/数据,另一个用于页面模板.这对我来说似乎效率低下,并且似乎不是一种非常可扩展的方法.
最近,我遇到了一个聪明的框架,它允许我将我的系统从randomPage.php和randomPage.tpl整合成类似的东西:
randomSmartyPage.php
{extends file="template.tpl"}
{block name=pageTitle}My Page Title{/block}
{block name=pageResources}
<link href="/css/someRandomCSS.css" rel="stylesheet" text="text/css">
{/block}
{block name=pageContent}My HTML Page Body goes here{/block}
Run Code Online (Sandbox Code Playgroud)
看到这种方法为我提出了三个主要问题:
这是一个未经测试的例子.它将封装所有变量,因此您不会污染全局命名空间.
function view($file, $vars) {
ob_start();
extract($vars);
include dirname(__FILE__) . '/views/' . $file . '.php';
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
echo view('home', array('content' => Home::getContent()));
Run Code Online (Sandbox Code Playgroud)
<h1>Home</h1>
<?php echo $content; ?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2238 次 |
| 最近记录: |