如何正确缩进PHP / HTML混合代码? [英] How to properly indent PHP/HTML mixed code?

查看:100
本文介绍了如何正确缩进PHP / HTML混合代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

混合使用PHP和HTML时,使用什么样的缩进风格?我是否缩进,以便输出的HTML具有正确的缩进,或者PHP / HTML混合看起来是正确格式化的(因此更容易阅读)?

例如,说我有一个 foreach 循环输出表行。下面哪一个是正确的?



PHP / HTML组合看起来正确:

 <表> 
<?php foreach($ rows as $ row):?>
< tr>
<?php if($ row-> foo()):?>
<?php echo $ row?>
<?php else:?>
其他
<?php endif?>
< / tr>
<?php endforeach?>
< / table>

输出的HTML看起来正确:

 < table> 
<?php foreach($ rows as $ row):?>
< tr>
<?php if($ row-> foo()):?>
<?php echo $ row?>
<?php else:?>
其他
<?php endif?>
< / tr>
<?php endforeach?>
< / table>

我发现当我遇到这种情况时(相当频繁),我没有一个标准的风格使用。我知道可能没有正确的答案,但我很乐意听到其他开发人员的想法。 解决方案

PHP和HTML都应该缩进,以便它们在源代码中相对于自己是正确的,而不管相互之间以及输出的形式如何:

 <表> 
<?php foreach($ rows as $ row):?>
< tr>
<?php if($ row-> foo()):?>
<?php echo $ row?>
<?php else:?>
其他
<?php endif?>
< / tr>
<?php endforeach?>
< / table>


When mixing PHP and HTML, what is the proper indentation style to use? Do I indent so that the outputted HTML has correct indentation, or so that the PHP/HTML mix looks properly formatted (and is thus easier to read)?

For example, say I have a foreach loop outputting table rows. Which one below is correct?

PHP/HTML mix looks correct:

<table>
  <?php foreach ($rows as $row): ?>
    <tr>
      <?php if ($row->foo()): ?>
        <?php echo $row ?>
      <?php else: ?>
        Something else
      <?php endif ?>
    </tr>
  <?php endforeach ?>
</table>

Outputted HTML looks correct:

<table>
<?php foreach ($rows as $row): ?>
  <tr>
  <?php if ($row->foo()): ?>
    <?php echo $row ?>
  <?php else: ?>
    Something else
  <?php endif ?>
  </tr>
<?php endforeach ?>
</table>

I've found that when I run into this situation (quite frequently), I don't have a standard style to use. I know that there may not be a "correct" answer, but I'd love to hear thoughts from other developers.

解决方案

The PHP and the HTML should each be indented so that they are correct with respect to themselves in source form, irrespective of each other and of outputted form:

<table>
<?php foreach ($rows as $row): ?>
    <tr>
    <?php if ($row->foo()): ?>
        <?php echo $row ?>
    <?php else: ?>
        Something else
    <?php endif ?>
    </tr>
<?php endforeach ?>
</table>

这篇关于如何正确缩进PHP / HTML混合代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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