lnear/html

用于渲染 HTML 的实用函数

1.1.3 2024-07-18 20:41 UTC

This package is auto-updated.

Last update: 2024-09-10 06:04:44 UTC


README

此库提供了一组函数,用于根据 HTML 生活标准 生成 HTML 元素及其属性。

安装

要安装此库,请使用以下命令

composer require lnear/html

用法

库提供了以 HTML 元素命名的函数,这些函数接受属性作为命名参数。有两大命名空间可用:htmlhtml\strict

  • html\strict 命名空间:仅允许元素根据 HTML 生活标准有效的属性。
  • html 命名空间:更宽容,允许将任何属性传递给函数。自定义属性名称应采用驼峰式。

示例

// Using the strict namespace
html\strict\a(href: 'https://example.com', dataFoo: 'bar'); // Throws an InvalidArgumentException

// Using the permissive namespace
html\a(href: 'https://example.com', dataFoo: 'bar'); // <a href="https://example.com" data-foo="bar"></a>

除了属性限制外,这两个命名空间的功能相同。以下示例使用 html 命名空间,但您可以使用 html\strict 命名空间来强制执行 HTML 标准。

data-* 属性

要使用 html\strict 命名空间传递 data-* 属性,请使用 dataset 属性作为键为属性名称(不带 data- 前缀)的关联数组。

use function html\strict\a;

echo a(href: 'https://example.com', dataset: ['fooBar' => 'baz']); // <a href="https://example.com" data-foo-bar="baz"></a>
echo a(href: 'https://example.com', dataset: ['fooBar' => 'baz', 'barFoo' => 'qux']); // <a href="https://example.com" data-foo-bar="baz" data-bar-foo="qux"></a>

所有函数都返回代表它们所表示 HTML 元素的 Stringable 类(html\RenderResult)。唯一的例外是 var 函数,其名称为 variable 以避免与保留关键字 var 冲突。

Body 参数

body 参数存在于所有非自闭合元素中,用于在元素内添加文本或其他元素。

use function html\div;

echo div(body: 'Hello, World!'); // <div>Hello, World!</div>

body 参数也是这些函数的第一个参数,因此可以省略参数名称。

use function html\div;

echo div('Hello, World!'); // <div>Hello, World!</div>

嵌套元素

可以通过嵌套函数来创建更复杂的元素,其中 body 参数是元素数组的。

use function html\{div, a, p};

echo div(
    class: 'container', 
    body: [
        a('Click me!', href: 'https://example.com', target: '_blank', rel: 'noopener noreferrer'),
        p('This is a paragraph.')
    ]
);

// <div class="container"><a href="https://example.com" target="_blank" rel="noopener noreferrer">Click me!</a><p>This is a paragraph.</p></div>

编码

html\RenderResult 类实现了 Stringable 接口,允许其在任何期望字符串的上下文中使用。它还可以用于绕过字符串的 HTML 编码。

use function html\{div, RenderResult};

$unsafe = '<script>alert("XSS")</script>';

echo div(body: $unsafe); // Default encoding: &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;

$safe = RenderResult::wrap($unsafe); // Explicit encoding

echo div(body: $safe); // No double encoding: <div>&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;</div>

$byPass = RenderResult::encoded($unsafe); // String already encoded

echo div(body: $byPass); // <div><script>alert("XSS")</script></div>

// Or use the bypass helper function
use function html\bypass;
echo div(body: bypass($unsafe)); // <div><script>alert("XSS")</script></div>

元素

所有元素都共享以下全局属性

以下元素仅具有全局属性

以下元素具有附加属性