开发者

Separate Logic from presentation without using template engine

开发者 https://www.devze.com 2022-12-25 20:31 出处:网络
How can we separate Logic from presentation without using any temp开发者_JAVA技巧late engine (traditional php-not OOP)

How can we separate Logic from presentation without using any temp开发者_JAVA技巧late engine (traditional php-not OOP) Thank in advance


Why not to use PHP itself as a template engine? It being used in the code I posted for your other question. Your program has to be split into 2 main sections: getting data and displaying data.

Each page have to have it's own template. In the code I posted there is 2 very simple templates, form.php and list.php
just extend it with the whole site template, And you have done!
Here is a little more complex PHP template example:

<table border="0" cellpadding="2" cellspacing="0" width="600">
<? foreach ($data as $row): ?> 
  <tr bgcolor="#666699">
    <td align=left>
      <font color="white"><b><?=$row['name']?></b></font>
    </td>
    <td align=right><font color="white">
      <?=$row['date'] ?>
    </font></td>
  </tr>
  <tr bgcolor="f0f0f0">
    <td colspan=2><?=$row['body'] ?></td>
  </tr>
  <? if ($row['answer']): ?>
  <tr bgcolor="d3d3d3">
    <td colspan=2 valign="top">
      <table border="0" cellpadding="0" cellspacing="5">
        <tr>
          <td valign="top"><b>Answer: </b></td>
          <td><?=$row['answer'] ?></td>
        </tr>
      </table>
    </td>
  </tr>
  <? endif ?>
  <? if($admin): ?>
  <tr>
    <td colspan=2>
      <font size=-1>
      <?=$row['id']?> - <?=$row['ip']?> - <?=$row['topic']?>
  <? if($row['del']): ?>
      <a href="/gb/?action=show&id=<?=$row['id']?>">show</a>
  <? else: ?>
      <a href="/gb/?action=hide&id=<?=$row['id']?>">hide</a>
  <? endif ?>
      <a href="/gb/?action=edit&id=<?=$row['id']?>">edit</a>
      </font>
    </td>
  </tr>
  <? endif ?>
<? endforeach ?>
</table>

And it is called like this

<?
//some code to get data
include 'tpl_top.php';
include 'tpl_list.php';
include 'tpl_bottom.php';
?>

Looks magnificent to me!
Dunno though, if it's what you're asking for :)


PHP itself can be used as a template engine. Just put all your logic before you output anything. Put simply:

  1. Process your input
  2. Assign all the dynamic data to be output to variables
  3. Run your view code. The view code may be in a separate file which you include.
  4. In the view, just use things such as echo and foreach to output the data you put into variables in step 2.
0

精彩评论

暂无评论...
验证码 换一张
取 消