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>
修正思路与建议
区分内容类型处理换行缩进
- 当
$content包含子元素(即内容里有换行和缩进)时,在闭合标签前添加换行和对应层级的缩进; - 当
$content是纯文本无换行时,保持闭合标签与内容同行即可。
可以通过判断$content中是否包含换行符"\n"来区分:
// 在拼接闭合标签前添加判断 if (str_contains($content, "\n")) { $output .= "\n" . str_repeat(" ", $this->tabs + $tabcount); } $output .= "</div>";- 当
统一换行符处理
确保所有换行使用一致的"\n",避免混合使用不同换行符导致判断失效。同时注意初始$output的换行不要产生多余空行,可将初始行改为:$output = str_repeat(" ", $this->tabs + $tabcount) . "<div";然后在调用
getHtmlDiv时,由上层负责添加换行,避免嵌套时产生多余空行。层级缩进计算校验
确认$this->tabs和$tabcount的层级计算正确,比如父元素的tabcount应该比子元素小1,确保闭合标签的缩进与起始标签一致。
内容的提问来源于stack exchange,提问作者julio
相关产品推荐
相关产品推荐

