我不打算仅针对PHP选择模板引擎.我选择不使用像Smarty这样的模板引擎,因为我想学习如何使用PHP和HTML正确设计模板.有人可以提供有关如何设计模板页面的链接或示例吗?
Ric*_*nop 17
只需为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; ?>
Run Code Online (Sandbox Code Playgroud)
我还建议为非常相似的HTML输出创建视图助手,并使用它们而不是重复的HTML代码.
这真的不是那么困难.
Non-PHP goes out here
<?php # PHP goes in here ?>
More non-PHP goes out here
<?php # More PHP goes in here ?>
Run Code Online (Sandbox Code Playgroud)
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!');
Run Code Online (Sandbox Code Playgroud)
我的框架我有加载视图的功能,然后在布局中将其删除:
public function returnView(){
ob_start();
$this->loader();
$this->template->show($this->controller,$this->action);
return ob_get_clean();
}
Run Code Online (Sandbox Code Playgroud)
布局看起来像这样:
<html>
<head>
<title><?php echo $this->layout('title'); ?></title>
</head>
<body>
<?php echo $this->layout('content'); ?>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6814 次 |
| 最近记录: |