Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 73905

PHP code for attributes inside HTML opening tag

$
0
0

I know of this method which enables us to use PHP variables / statements for values of HTML attributes.

<button type="button" data-value="<?= $value; ?>">Remove</button>

But I am wondering what the best practices are for adding them as attributes. (I'll just mix in various examples to show why I need to do that).


(1)

This works, but Sublime's syntax highlighter marks it as an error, which is why this pains me to use.

<?php
$attributes = array(
    'title="Lorem ipsum"',
    'style="background-color: red;"',
);
if ($is_special_case) {
    array_push($attributes, 'data-case="special"');
}
$attributes = implode('', $attributes);
?>
<button type="button"<?= $attributes; ?>>Remove</button>

(2)

In researching this, I learned of this alternative – but it seems to have the same problem: it works even though Sublime detects faulty syntax.

<?php
    $tmp = ' disabled';
    echo <<<HTML
        <button type="button" ${tmp}>Remove</button>
HTML;
?>

(Adding ?> behind the first HTMLallegedly fixes this, but I cannot confirm.)

(3)

Instead, I am currently using this method.

<?php echo sprintf(`
        <button type="button" %s>Remove</button>
    `,
    ($is_disabled   ? 'disabled'   : '')
); ?>

But it adds further layers of indentation, is so much harder to read, and overall feels clunky.


Is there a better, or agreed upon alternative? Or is the first method the best one, and I just need to modify Sublime somehow / file a bug report?

(Sublime 3.2.2 Build 3211)


Viewing all articles
Browse latest Browse all 73905

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>