使用PHP和HTML时最佳做法是什么? [英] What is the best practice to use when using PHP and HTML?

查看:121
本文介绍了使用PHP和HTML时最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在设计网站一段时间,但有一件事,我从来没有确定使用PHP和HTML。在PHP中使用整个文档和 echo > HTML是更好的方法:

 <?php 
doSomething();
echo< div id = \some_div \> Content< / div>;
?>

或者像这样的HTML文件,只需在PHP中添加:

 < html> 
< body>
<?php doSomething(); ?>
< div id =some_div>内容< / div>
< / body>
< / html>

对于 echo 如果在整个页面中使用了大量的PHP,但是这样做会丢失所有的HTML格式,例如IDE中的颜色等等。 解决方案

对此有不同的意见。我认为有两个好方法:

$ ul

  • .netrel =noreferrer> Smarty 完全分离代码和表示。 使用你的第二个例子,但是当把PHP混合成HTML时,只有输出变量 。在输出任何东西或单独的文件之前,执行一个块中的所有代码逻辑。像这样:

     <?php $ content = doSomething(); 
    //复杂计算
    ?>
    < html>
    < body>
    <?php echo $ content; ?>
    < div id =some_div>内容< / div>
    < / body>
    < / html>




  • 大多数成熟的应用程序框架都带有自己的这样做的风格;在这种情况下,通常最好按照提供的样式。


    I have been designing websites for a while now, but there is one thing that I have never been quite sure of when using PHP and HTML. Is it better to have the whole document in PHP and echo HTML like so:

    <?php
      doSomething();
      echo "<div id=\"some_div\">Content</div>";
    ?>
    

    Or have a HTML file like so and just add in the PHP:

    <html>
    <body>
      <?php doSomething(); ?>
      <div id="some_div">Content</div>
    </body>
    </html>
    

    It seems tidier to echo HTML, especially if lots of PHP gets used throughout the page, but doing so loses all formatting of the HTML i.e. colors in the IDE etc.

    解决方案

    There are varying opinions on this. I think there are two good ways:

    • Use a templating engine like Smarty that completely separates code and presentation.

    • Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:

      <?php $content = doSomething();
         // complex calculations
      ?>
      <html>
      <body>
        <?php echo $content; ?>       
        <div id="some_div">Content</div>
      </body>
      </html>
      

    Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.

    这篇关于使用PHP和HTML时最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆