如何将 PHP 代码用于 HTML 开始标记内的属性

我知道这种方法使我们能够将 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。


隔江千里
浏览 136回答 1
1回答

回首忆惘然

您不必要地使示例 #2 复杂化。尝试这个:<?php&nbsp; &nbsp; $tmp = 'disabled';&nbsp; &nbsp; echo <<<HTML&nbsp; &nbsp; &nbsp; &nbsp; <button type="button" $tmp>Remove</button>HTML;?>如果它真的是一行 HTML,甚至更好:<?php&nbsp; &nbsp; $tmp = 'disabled';&nbsp; &nbsp; echo "<button type='button' $tmp>Remove</button>"?>(如果您只是必须在 HTML 中使用双引号,请使用:echo "<button type=\"button\" $tmp>Remove</button>"
打开App,查看更多内容
随时随地看视频慕课网APP