Templating

Mixing PHP and HTML

Use discreet PHP blocks interspersed among HTML elements (not HTML concatenated into PHP statements). Although this results in more PHP demarcation tags, it’s more readable.

<!-- Good -->
<h1><?php echo $title; ?></h1>

<!-- Bad -->
<?php echo "<h1>" . $title . "</h1>"; ?>

Nesting PHP and HTML

Nested template code should follow programmatic hierarchy (not output hierarchy). Since HTML collapses whitespace there is no advantage to preserving the output markup’s hierarchy.

<!-- Good -->
<div>
    <h2>Title</h2>

    <?php if ($x): ?>
        <p>Something.</p>
    <?php endif; ?>
</ul>

<!-- Bad -->
<div>
    <h2>Title</h2>

<?php if ($x): ?>
    <p>Something.</p>
<?php endif; ?>
</ul>

<!-- Bad -->
<div>
    <h2>Title</h2>

    <?php if ($x): ?>
    <p>Something.</p>
    <?php endif; ?>
</ul>