How to properly indent PHP/HTML mixed code? [closed]
Asked Answered
P

6

68

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.

Print answered 20/7, 2009 at 20:30 Comment(0)
B
53

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>
Bonilla answered 20/7, 2009 at 20:33 Comment(4)
How would you do it in case you want to get a string containing the table instead of echoing it?Orit
@Dane411: If you're building the string using heredoc syntax, indent it as HTML. If you're building it out of small inline strings, forget about the HTML indentation, because visual comprehensibility of the HTML content is already a wash and belaboring the situation with more awkward conventions isn't going to help anything.Bonilla
Is there a commonly accepted style guide that advocates for this approach?Trompe
when mixing php with html you can refer the alternative control structure hereEgotist
D
17

I often pondered this question too, but then I realized, who cares what the HTML output looks like? Your users shouldn't be looking at your HTML anyway. It's for YOU to read, and maybe a couple other developers. Keep the source code as clean as possible and forget about what the output looks like.

If you need to debug the output, use Chrome Developer Tools, Firebug, or even F12 Tools.

Dextrocular answered 21/7, 2009 at 5:31 Comment(0)
S
12

I generally put opening php tags at the beginning of the line, but indent whatever is inside the tags to match the html formatting. I don't do this, however, for simple echo statements since I use short-open tags. I think it makes simpler it when browsing through the file to find all the declarations.

    <table>
<?  foreach ($foo as $bar): ?>
      <tr>
<?    foreach ($bar as $baz): ?>

         <td><?=$baz?></td>

<?    endforeach ?>
      </tr>
<?  endforeach ?>
    </table>
Sammie answered 20/7, 2009 at 20:38 Comment(6)
+1: This is how I actually write (well, except I use braces, not colon/end form, and four spaces per indent level); I just adapted OP's conventions for convenience.Bonilla
I got out of this habit as it makes it a lot harder to quickly scan through your page.Gallo
You should not use the short opening tags. You can run into various problems with your code connected to the php setting short_open_tag.Popp
@markus: As it says on my Wikipedia userpage, you can have my short tags when you pry them from my cold, dead hands. And seriously, I think I'm capable of coping with the XML version tag thing.Bonilla
If you wish to follow PSR-2, you can only use short tags in conjunction with the echo shorthand syntax (long tags everywhere else).Galahad
what I like about this convention of putting "<?" at the start of the line is that the PHP is more readable (not visually cluttered by otherwise near "<?" sign) and that it makes it easier for my brain to switch between reading HTML and PHP separately - I instantly know if the line I'm reading belongs to the one or the other world. Great!Morelli
S
4
  1. Direct answer to your question: If you need to read the HTML output often, it might be a good thing to output well indented HTML. But the more common case will be that you need to read your php source code, so it is more important that the source is easily readable.
  2. Alternative to the two options you mentioned: See chaos' or tj111's answer.
  3. Better still in my opinion: Don't mix HTML and php, use a template engine instead.
Stacte answered 20/7, 2009 at 20:40 Comment(3)
Thanks for the comments Treb. Even if I used a templating engine, the question would still exist: how to properly indent HTML/templating engine tags.Print
PHP is a templating engine. :)Bonilla
@chaos: I knew that answer would come... Maybe it is, but what I see in the example codes here is not a proper use of a template engine, but a bad mixture of code and design.Stacte
S
2

You can always use a bit of whitespace too to help readability. Building on chaos' indentation:

<table>

<?php foreach ($rows as $row): ?>

    <tr>

    <?php if ($row->foo()): ?>
        <?php echo $row ?>
    <?php else: ?>

        Something else

    <?php endif ?>

    </tr>

    <?php endforeach ?>

</table

The only downside with this is if you have a lot of mixed code it can make your document twice as long, which makes for more scrolling. Although if you have this much mixed code you may want to consider a templating engine.

Seminal answered 20/7, 2009 at 20:41 Comment(2)
You just added some line breaks....that don't really add to the clarity at all IMHO. Get a decent IDE and it should color it nicely for you.Dextrocular
This really is an entirely subjective matter, so of course what may be an aide for some wont do a thing for others. :)Seminal
M
2

You should not be bothered about markup indentation in the production environment. Neither should you use Tidy or other HTML purifiers. There are valid use cases, e.g. when you allow HTML input (but consider using Markdown instead), though these are rare.

Most often HTML beautifiers-filters are abused to hide the underlying issues with the code. Don't. Correct your markup manually.

If you need to indent your code only in the development environment, you can use either of the above. However, beware that these libraries will attempt to fix your markup (that's their primary purpose; indentation is a by-product). I've written Regular Expression based indentation tool Dindent.

Dindent will convert markup like this:

<!DOCTYPE html>
<html>
<head></head>
<body>
    <script>
    console.log('te> <st');
    function () {
        test; <!-- <a> -->
    }
    </script>
    <div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <div><table border="1" style="background-color: red;"><tr><td>A cell    test!</td>
<td colspan="2" rowspan="2"><table border="1" style="background-color: green;"><tr> <td>Cell</td><td colspan="2" rowspan="2"></td></tr><tr>
        <td><input><input><input></td></tr><tr><td>Cell</td><td>Cell</td><td>Ce
            ll</td></tr></table></td></tr><tr><td>Test <span>Ce       ll</span></td></tr><tr><td>Cell</td><td>Cell</td><td>Cell</td></tr></table></div></div>
</body>
</html>

To this:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <script>
    console.log('te> <st');
    function () {
        test; <!-- <a> -->
    }
    </script>
        <div>
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
            <div>
                <table border="1" style="background-color: red;">
                    <tr>
                        <td>A cell test!</td>
                        <td colspan="2" rowspan="2">
                            <table border="1" style="background-color: green;">
                                <tr>
                                    <td>Cell</td>
                                    <td colspan="2" rowspan="2"></td>
                                </tr>
                                <tr>
                                    <td>
                                        <input>
                                        <input>
                                        <input>
                                    </td>
                                </tr>
                                <tr>
                                    <td>Cell</td>
                                    <td>Cell</td>
                                    <td>Ce ll</td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <tr>
                        <td>Test <span>Ce ll</span></td>
                    </tr>
                    <tr>
                        <td>Cell</td>
                        <td>Cell</td>
                        <td>Cell</td>
                    </tr>
                </table>
            </div>
        </div>
    </body>
</html>

Dindent will not attempt to sanitise or otherwise interfere with your code beyond adding indentation. This is to make your development/debugging easier. Not for production.

Mutinous answered 19/2, 2014 at 22:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.