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

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

问题描述

我设计网站已经有一段时间了,但是在使用 PHP 和 HTML 时,我一直不太确定一件事.将整个文档放在 PHP 和 echo 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>";
?>

或者有一个这样的 HTML 文件,只需添加 PHP:

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>

echo HTML 似乎更整洁,尤其是在整个页面使用大量 PHP 时,但这样做会丢失 HTML 的所有格式,即 IDE 中的颜色等.

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:

  • 使用像 Smarty 之类的模板引擎,将代码和表示完全分离.

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

使用您的第二个示例,但是当将 PHP 混合到 HTML 中时,仅输出变量.在输出任何内容或单独的文件之前,在一个块中执行所有代码逻辑.像这样:

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天全站免登陆