我不想就只使用PHP来争论选择模板引擎的问题。我选择不使用像Smarty这样的模板引擎,因为我想学习如何使用PHP和HTML来正确设计模板。是否有人能提供关于如何设计模板页面的链接或示例?
只需使用专门为此目的设计的if/for/foreach控制语言结构的替代PHP语法:
<h1>Users</h1>
<?php if(count($users) > 0): ?>
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user): ?>
<tr>
<td><?php echo htmlentities($user->Id); ?></td>
<td><?php echo htmlentities($user->FirstName); ?></td>
<td><?php echo htmlentities($user->LastName); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p>No users in the database.</p>
<?php endif; ?>
这并不是很难。
Non-PHP goes out here
<?php # PHP goes in here ?>
More non-PHP goes out here
<?php # More PHP goes in here ?>
function returnView($filename,$variables){
ob_start();
$htmlfile = file_get_contents($filename);
foreach($variables as $key=>$value){
$htmlfile = str_replace("#".$key."#", $value, $htmlfile);
}
echo $htmlfile;
return ob_get_clean();
}
//htmlfile
<html>
<title>#title#</title>
</html>
//usage
echo returnView('file.html',array('title'=>'hello world!');
public function returnView(){
ob_start();
$this->loader();
$this->template->show($this->controller,$this->action);
return ob_get_clean();
}
布局看起来像这样:
<html>
<head>
<title><?php echo $this->layout('title'); ?></title>
</head>
<body>
<?php echo $this->layout('content'); ?>
</body>
</html>
<h1>Users</h1>
<? if(count($users) > 0): ?>
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<? foreach($users as $user): ?>
<tr>
<td><?= htmlentities($user->Id) ?></td>
<td><?= htmlentities($user->FirstName) ?></td>
<td><?= htmlentities($user->LastName) ?></td>
</tr>
<? endforeach ?>
</tbody>
</table>
<? else: ?>
<p>No users in the database.</p>
<? endif ?>
echo
简写和添加一些分号不值得为一个六年前的问题写一个新答案,兄弟。 - Marijan我使用过各种模板引擎,并且还设计了自己的模板引擎,随着时间的推移变得越来越复杂。我认为最好使用本地 PHP 来保持尽可能简单,而不是创建复杂的函数(这篇文章提出了一些好的观点:Boring Architecture is Good)。我发现当几个月或几年后回到项目时,代码更易读和维护。
例如:
<?
$name="john";
$email="john@xyz.com";
require "templates/unsubscribe.php";
-- 模板/取消订阅.php --
<?
$o=<<<EOHTML
Hi $name, sorry to see you go.<BR>
<input type=input name=email value=$email>
<input type=submit value='Unsubscribe'>
EOHTML;
echo $o;
如果您选择采用MVC风格的方法,您可能需要考虑的是,如果您将模板包含在对象内部(其中一个类方法),那么模板文件中的$this
将指向您从中调用它的对象。
如果您希望确保模板的某种封装性,即如果您不想依赖全局变量来传递动态数据(例如来自数据库的数据),则这非常有用。
<?= $var?>
)中?您是否接受循环遍历数组的方式? 或者,您想让模板没有PHP并以另一种方式替换变量。您似乎了解一些模板引擎。为什么不查看源代码并学习它们的工作方式。比起抱怨别人没有在第一次回复中发布完整的TE,这样做更好。 - GolezTrol