You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP Div样式表格渲染类:闭合标签缩进错误问题求助

修复Div表格渲染的缩进问题

当前渲染出的表格结构存在缩进错误:

<div class="table">
    <!-- title, column headers -->
    <div class="table-body">
        <div class="table-row">
            <div class="table-row-cell">data11</div>
            <div class="table-row-cell">data12</div>
            <div class="table-row-cell">data13</div></div> <!-- this -->
        <div class="table-row">
            <div class="table-row-cell">data21</div>
            <div class="table-row-cell">data22</div>
            <div class="table-row-cell">data23</div></div> <!-- and this -->
    </div>
    <!-- footer -->
</div>

可见table-row的闭合<div>标签未正确换行并缩进。

现有构建Div的代码

public function get(): string
{
    // some code and loops

    $row_build .= $this->getHtmlDiv(
                            $html_cell_class,
                            $cell_data ?? "",
                            $this->html_attributes['cell'],
                            3
                        );
    // more code
}

private function getHtmlDiv(
    string $class,
    string $content = "",
    array $attrs = [],
    int $tabcount = 0
): string {
    $output = "
" . str_repeat("    ", $this->tabs + $tabcount) . "<div";

    $output .= " class='$class'";

    foreach ($attrs as $attr => $value) {
        $output .= " $attr='$value'";
    }

    $output .= ">";
    $output .= $content;
    $output .= "</div>"; // <- here something should be done: what? IDK
    return $output;
}

已尝试的修改方案

在return $output;前添加以下代码:

if (substr($output, -2) !== "
") {
    $output .= "
" . str_repeat("    ", $this->tabs + $tabcount - 1);
}

渲染结果如下(虽有改善但仍存在多余空行):

<div class='table-row'>
                
    <div class='table-row-cell'>data21</div>
                
    <div class='table-row-cell'>data22</div>
                
    <div class='table-row-cell'>data23</div>

</div>

修正思路与建议

  1. 区分内容类型处理换行缩进

    • 当$content包含子元素(即内容里有换行和缩进)时,在闭合标签前添加换行和对应层级的缩进;
    • 当$content是纯文本无换行时,保持闭合标签与内容同行即可。
      可以通过判断$content中是否包含换行符"\n"来区分:
    // 在拼接闭合标签前添加判断
    if (str_contains($content, "\n")) {
        $output .= "\n" . str_repeat("    ", $this->tabs + $tabcount);
    }
    $output .= "</div>";
    
  2. 统一换行符处理
    确保所有换行使用一致的"\n",避免混合使用不同换行符导致判断失效。同时注意初始$output的换行不要产生多余空行,可将初始行改为:

    $output = str_repeat("    ", $this->tabs + $tabcount) . "<div";
    

    然后在调用getHtmlDiv时,由上层负责添加换行,避免嵌套时产生多余空行。

  3. 层级缩进计算校验
    确认$this->tabs和$tabcount的层级计算正确,比如父元素的tabcount应该比子元素小1,确保闭合标签的缩进与起始标签一致。

内容的提问来源于stack exchange,提问作者julio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 02:17:28