开发者

What's the best way to format long strings of HTML in PHP?

开发者 https://www.devze.com 2022-12-24 00:58 出处:网络
I know it\'s really a subjective question, but for best-practices (and readability), I can\'t seem to get a fix on the best way to format long strings of HTML. I typically do it like this:

I know it's really a subjective question, but for best-practices (and readability), I can't seem to get a fix on the best way to format long strings of HTML. I typically do it like this:

echo '
<div>
    <p>Content Inside</p>
    <div class="subbox">
        <ul>
            <li>etc.</li>
            <li>etc.</li>
            <li>etc.</li>
         开发者_Python百科   <li>etc.</li>
        </ul>
    </div>
</div>
';

But I still don't like the outcome, especially if this appears in the middle of a large block of code. It just feels messy.


You can jump out of PHP and input HTML directly:

<?php $var = "foo"; ?>
<div>
  <ul>
    <li>Foo</li>
  </ul>
</div>
<?php $foo = "var"; ?>

If all you're doing is an echo/print, I think this is much cleaner. Furthermore, you don't need to run through and escape single/double quotes within the HTML itself.

If you need to store the HTML in a variable, you could use HEREDOC:

$str = <<<EOD
<div>
  <ul>
    <li>Foo</li>
  </ul>
</div>
EOD;


Why not just embed your PHP in the HTML? That's how PHP was originally designed to work.

// PHP goes here
?>
<div>
    <p>Content Inside</p>
    <div class="subbox">
        <ul>
            <li>etc.</li>
            <li>etc.</li>
            <li>etc.</li>
            <li>etc.</li>
        </ul>
    </div>
</div>
<?php
// More PHP here


Old school Perl-style heredoc works too:

echo <<<EOL
<div>
    <p>Content Inside</p>
    <div class="subbox">
        <ul>
            <li>etc.</li>
            <li>etc.</li>
            <li>etc.</li>
            <li>etc.</li>
        </ul>
    </div>
</div>
EOL;

Using multiple <?php ?> blocks is cleaner, but if you're in a class definition or something, a heredoc might be less awkward (though printing HTML from a class definition is nothing but awkward).


I would do it like this:

echo '<div>
         <p>Content Inside</p>
         <div class="subbox">
             <ul>
                 <li>etc.</li>
                 <li>etc.</li>
                 <li>etc.</li>
                 <li>etc.</li>
            </ul>
         </div>
      </div>';


I prefer an MVC architecture like Code Igniter for separating presentation from logic. Basically, all your templates are stored separately and you use the PHP alternate syntax structures described here to format your HTML.


The best way is to use a templating system where you can separate your logic from presentation. In the template you'd only have stuff like:

<html>
<body>

<h1><?php echo $title; ?></h1>
<p><?php echo $myparagraph; ?></p>

</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消