我正在寻找一个轻量级的、基于PHP的布局框架。就像Zend Framework使用布局一样,我希望创建一个布局模板,只包含必要页面的内容。
<html>
<head>
<title><?= $pageTitle ?></title>
</head>
<body>
<?= $content ?>
</body>
</html>
有人知道有什么工具可以实现这个吗?我想使用Zend框架,但它对我想要实现的功能来说太过庞大了。
我正在寻找一个轻量级的、基于PHP的布局框架。就像Zend Framework使用布局一样,我希望创建一个布局模板,只包含必要页面的内容。
<html>
<head>
<title><?= $pageTitle ?></title>
</head>
<body>
<?= $content ?>
</body>
</html>
有人知道有什么工具可以实现这个吗?我想使用Zend框架,但它对我想要实现的功能来说太过庞大了。
我支持PHP。(PHP 是一个模板引擎。)
function template($file, $vars) {
ob_start();
if(count($vars) > 0) { extract($vars); }
include 'views/'.strtolower($file).'.php';
return ob_get_clean();
}
顺便提一下,这让你能够做以下事情。
echo template('layout', array( 'content' => template('page', $myData) ));
当PHP本身只需要6行就可以胜任时,你是否还应该使用其他模板/布局引擎呢?
编辑:
也许我没有清楚地表达这个工作原理。
template()
以模板名称(子目录用于组织也可以)作为第一个参数,数组对象作为第二个参数进行调用。如果给定的变量不为空,例如template('index',null)
,则该数组被视为关联数组:每个键都包含值的变量。
因此逻辑变为:
template('my_template', array(
'oranges' => 'apples'
));
而 "views/my_template.php" 是:
<html>
<head>
<title>Are apples == <?= $oranges ?>?</title>
</head>
<body>
<p style="color: <?= $oranges == 'oranges' ? 'orange" : 'darkgreen' ?>">
Are apples == oranges?
</p>
</body>
</head>
$oranges
时,PHP都会获取从数组$vars['oranges']
导出的数据。然后,所有输出都由ob_get_clean()
获取并返回为字符串。要输出此字符串,只需使用echo
或print
,或将其分配给数组以作为内容传递给布局。如果您理解了这一点,那么很容易根据我所写的内容制作布局,甚至可以输出JSON的具有逻辑的页面。
在放弃此答案之前,我建议您尝试进行实验。它有增长的倾向。
编辑2:
按照要求,我将展示我的项目将使用的目录布局。请注意,其他MVC框架使用不同的结构。但是,我喜欢我的简单性。
index.php
application/
framework.php
controllers/
welcome.php
views/
template.php
index.php
php_value auto_prepend_file prepend.php
php_value auto_append_file append.php
接下来在你的prepend.php文件中,你需要开启输出缓冲:
<?php
ob_start();
<?php
if (!isset($page_title)) {
$page_title = 'Default Page Title';
}
$content = ob_get_contents();
ob_end_clean();
?>
<html>
<head>
<title><?php echo $page_title; ?></title>
</head>
<body>
<?php echo $content ?>
</body>
</html>
在此之后,您可以正常编写每个页面。以下是一个示例index.php
<?php
$page_title = "Index Page!";
?>
<h1>This is the <?php echo __FILE__; ?> page</h1>
...还有一个例子other.php,它做了一些有趣的事情:
<?php
$page_title = "Secondary Page!";
?>
<h1>This is the <?php echo __FILE__; ?> page</h1>
<p>enjoy some PHP...</p>
<ol>
<?php for ($i = 1; $i <= 10; $i++) : ?>
<li><?php echo "$i $i $i"; ?></li>
<?php endfor ?>
</ol>
完成了。您可以在此基础上进行扩展,例如在prepend中初始化DB连接,但是在某些时候,您可能希望转移到更抽象的系统,该系统打破了URL到路径和文件的固定映射。
再提供一个框架的建议:CodeIgniter 是我个人认为非常好的,它采用 MVC 架构,因此您可以将文件作为视图输出,并且据说有很小的占用空间。它还内置了 template parser。
祝好!
我已经使用Smarty很长时间了。 它非常成熟,得到积极维护,并且得到广泛支持。
无论如何,在这里你会找到各种模板引擎: http://en.wikipedia.org/wiki/Template_engine_(web)
如果你点击语言列,你将轻松看到PHP可用的内容以及引擎之间的比较。
$layout
变量,以及一个页面标题,并让append文件require()你想要的特定布局。只要你正确设置了prepend和append文件的路径(手册上说“该文件被包含就像使用require()函数一样,所以使用include_path”),你在子目录中的文件就不会有问题。 - Sean McSomething