使用PHP作为模板引擎

Sho*_*hoe 5 php templates

我不打算仅针对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代码.

  • 为什么不提<?= ...?>(相当于<?php echo ...?>)?现在它在任何地方启用,似乎完全适合这个用例. (4认同)

Ign*_*ams 9

这真的不是那么困难.

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)

  • 不,我很认真.在没有模板引擎的情况下,这样做的方法是以这种方式混合PHP和基本输出. (8认同)
  • 唯一真正重要的是:始终记住,您应该尽可能少地使用模板中的PHP代码.在业务逻辑部分中定义所有必要的数据,在模板中评估无变量等. (3认同)

Edm*_*mhs 7

 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)