What is the best practice to use when using PHP and HTML?(使用 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 时使用的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 PHP 和 HTML 时使用的最佳实践是什么?
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
