Josh Harrison
Josh Harrison

Reputation: 5994

PSR-2 compatible inline PHP tags in HTML templates

PSR-2 doesn't mention anything that would apply to the use of inline php tags in HTML templates, yet the php-cs-fixer tool seems to have a standard for it.

This is my template file, before running php-cs-fixer on it:

<nav>
    <ul>
        <li>
            <a href="#">Link</a>
<?php
if (! empty($subnav)) {
?>
            <ul class="subnav">
<?php
    foreach ($subnav as $link) {
?>
                <li><?=$link?></li>
<?php
    }
?>
            </ul>
<?php
}
?>
        </li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
    </ul>
</nav>

And after running php-cs-fixer fix views/ui/nav.php --level=psr2:

<nav>
    <ul>
        <li>
            <a href="#">Link</a>
<?php
if (! empty($subnav)) {
    ?>
            <ul class="subnav">
<?php
    foreach ($subnav as $link) {
        ?>
                <li><?=$link?></li>
<?php

    }
    ?>
            </ul>
<?php

}
?>
        </li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
    </ul>
</nav>

This just looks wrong, so I must be missing something.

Upvotes: 4

Views: 3490

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

As requested: comment posted as answer:

PSR only applies to PHP code, it doesn't have anything to say regarding inline HTML, because the HTML simply isn't PHP.

The output you get merely adds whitespace where, according to the standard, there should be whitespace - New lines after an opening { - lines after an { are indented using 4 spaces - ...

That's why this:

<?php
if(!empty($subnav)){//note no spaces
?>

Will be changed to:

<?php
if (!empty($subnav)) {
    ?>

In your foreach code, you'll notice that the everything is already indented with 4 spaces, because the code is inside the if block.

Either way, if you're going to mix PHP into markup, it might be best to use the alternative, more template-friendly syntax:

<?php
if (!empty($subnav)):
?>
//markup
<?php
    foreach ($subnav as $link):
        //do stuff
?>
//markup
<?php
    endforeach;
endif;
?>

Note that the indentation of the closing tags will probably be altered still by php-cs-fixer. Maybe inlining the end<blockName>; like so:

<?php endforeach; ?>

Upvotes: 2

Related Questions