mallardduck/html-formatter

HTML美化器与压缩库,用于开发和测试。

1.0.1 2022-02-27 23:38 UTC

This package is auto-updated.

Last update: 2024-08-28 05:03:16 UTC


README

Unit tests Code analysis Coverage Status License: MIT

1. 它是什么

HTML Formatter 将美化或压缩您的 HTML 字符串以供开发和测试。专为那些苦于阅读模板引擎生成的标记的人设计。

2. 它不是什么

HTML Formatter 不会对您的输出进行清理或进行其他操作,仅限于缩进和空格替换。HTML Formatter 仅添加缩进,不会影响标记。

如果您想删除恶意代码或确保您的文档符合标准,请考虑以下替代方案

如果您需要在开发环境中格式化代码,请注意,之前提到的库将尝试修复您的标记。

3. 安装

此软件包可以通过 Composer 安装。

composer require mallardduck/html-formatter

4. 使用方法

use MallardDuck\HtmlFormatter\Formatter;

$input = 'This is your HTML code.';
$formatter = new Formatter();
$output = $formatter->beautify($input);

5. 配置

Formatter 使用 Simple config 来调整其配置设置。

5.1. 内联和块级元素

HTML 元素要么是“内联”元素,要么是“块级”元素。

内联元素只占用定义内联元素的标签所包围的空间。以下示例演示了内联元素的影响

<p>This is an <span>inline</span> element within a block element.</p>

块级元素占用其父元素(容器)的全部空间,从而创建一个“块”。浏览器通常在块级元素前后都显示新行。以下示例演示了块级元素的影响

<div>
    <p>This is a block element within a block element.</p>
</div>

HTML Formatter 将以下元素识别为“内联”

  • a, abbr, acronym, b, bdo, big, br, button, cite, code, dfn, em,
  • i, img, kbd, label, samp, small, span, strong, sub, sup, tt, var

这是 MDN 中定义的内联元素的一个子集。[MDN](https://mdn.org.cn/en-US/docs/Web/HTML/Inline_elements)。所有其他元素都视为块级。

您可以通过将它们添加到 inline.tag 选项中来设置额外的内联元素。

use MallardDuck\HtmlFormatter\Formatter;

$formatter = new Formatter();
$config = $formatter->getConfig();
$config->append('inline.tag', 'foo')->subtract('inline.tag', ['bar', 'baz']);
$formatter->setConfig($config);

5.2. 自闭合(空)元素

空元素是 HTML、SVG 或 MathML 中的元素,不能有任何子节点(即嵌套元素或文本节点)。

HTML Formatter 将以下元素识别为“内联”

  • area, base, br, col, command, embed, hr, img, input,
  • keygen, link, menuitem, meta, param, source, track, wbr,
  • animate, stop, path, circle, line, polyline, rect, use

这是 MDN 中定义的空元素的一个子集。[MDN](https://mdn.org.cn/en-US/docs/Glossary/empty_element)。所有其他元素都需要闭合标签。

您可以通过将它们添加到 self-closing.tag 选项中来设置额外的自闭合元素。

use MallardDuck\HtmlFormatter\Formatter;

$formatter = new Formatter();
$formatter->setConfig($formatter->getConfig()->append('self-closing.tag', ['foo', 'bar']));

5.3. 预格式化元素

特定元素将不会被格式化器触碰到。内置的预格式化元素包括

  • scriptpretextarea

您可以通过将它们添加到formatted.tag选项中,来排除额外的元素。

所有格式化标签的设置如下

您也可以更改特定标签的设置。例如,禁用script标签的cleanup-empty设置看起来是这样的

use MallardDuck\HtmlFormatter\Formatter;

$formatter = new Formatter();
$config = $formatter->getConfig();
$config->set('formatted.tag.script.cleanup-empty', false);
$formatter->setConfig($config);

5.4. 属性

格式化标签的附加设置如下

6. 方法

7. 致谢

感谢 Gajus Kuizinas 首先创建 gajus/dindent 以及所有不懈努力工作的其他开发者。HTML Formatter受到了Dindent的启发。