【问题标题】:How to use PHP code for attributes inside HTML opening tag如何将 PHP 代码用于 HTML 开始标记内的属性
【发布时间】:2020-01-02 16:25:18
【问题描述】:

我知道这种方法使我们能够将 PHP 变量/语句用于 HTML 属性的值:

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

我想知道将它们添加为属性的最佳做法是什么:

  1. 这可行,但 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>
    
  2. 在研究这个的过程中,我了解到了一个替代方案,但它似乎有同样的问题:即使 Sublime 检测到错误的语法,它也能工作:

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

    在第一个 HTML 后面添加 ?&gt; 应该可以解决此问题,但我无法确认。见“How do I get HTML syntax highlighting inside PHP strings & heredoc syntax?”。

  3. 相反,我目前正在使用这种方法:

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

    但它增加了更多的缩进层,它是不是更难阅读,而且整体感觉很笨重。

是否有更好的或商定的替代方案?还是第一种方法最好,我只需要以某种方式修改 Sublime,或者提交错误报告?

我正在使用 Sublime 3.2.2 Build 3211。

【问题讨论】:

  • Sublime 可能突出显示为 HTML 而不是 PHP。我敢打赌有一个设置说“对 *.html 文件使用 PHP 荧光笔”或类似的设置。

标签: php html sublimetext3


【解决方案1】:

你的例子中最好的方法是第一个,但是我建议你为你的 HTML 标签实现一个库(比如流行的 MVC 框架:Laravel Forms,Codeigniter Form Helper),例如,你可能有一个函数来创建一个带有很多可选属性的按钮,你应该在你的 HTML 文件中调用这个函数。它真的是可重用和可读的。

【讨论】:

    【解决方案2】:

    您不必要地使示例 #2 复杂化。试试这个:

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

    如果它真的是一行 HTML,甚至更好:

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

    (如果您只是必须在 HTML 中使用双引号,请使用:

    echo "<button type=\"button\" $tmp>Remove</button>"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      • 2014-04-05
      • 1970-01-01
      相关资源
      最近更新 更多