Separate Logic from presentation without using template engine

前端 未结 2 1679
长发绾君心
长发绾君心 2021-01-15 11:25

How can we separate Logic from presentation without using any template engine (traditional php-not OOP) Thank in advance

相关标签:
2条回答
  • 2021-01-15 11:35

    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 :)

    0 讨论(0)
  • 2021-01-15 11:36

    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 讨论(0)
提交回复
热议问题