我知道这种方法使我们能够将 PHP 变量/语句用于 HTML 属性的值:
<button type="button" data-value="<?= $value; ?>">Remove</button>
我想知道将它们添加为属性的最佳做法是什么:
这行得通,但 Sublime 的语法高亮标记将其标记为错误。有关屏幕截图,请参见https://www.shotroom.com/2137/NPu9x。
<?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>
在研究这个时,我了解到了一个替代方案,但它似乎有同样的问题:即使 Sublime 检测到错误的语法,它也能工作:
<?php
$tmp = ' disabled';
echo <<<HTML
<button type="button" ${tmp}>Remove</button>
HTML;
?>
在第一个 HTML 后面添加?>应该可以解决这个问题,但我无法确认。请参阅“如何在 PHP 字符串和 heredoc 语法中突出显示 HTML 语法? ”。
相反,我目前正在使用这种方法:
<?php echo sprintf(`
<button type="button" %s>Remove</button>
`,
($is_disabled ? 'disabled' : '')
); ?>
但它增加了更多的缩进层,它是不是更难阅读,整体感觉很笨重。
是否有更好的或商定的替代方案?还是第一种方法是最好的,我只需要以某种方式修改 Sublime,或者提交错误报告?
我正在使用 Sublime 3.2.2 Build 3211。
回首忆惘然