kylerkatarnls/html-object

一套用于创建和操作HTML对象抽象的类

1.5.2 2023-03-02 15:22 UTC

This package is auto-updated.

Last update: 2024-08-30 01:26:41 UTC


README

Unit tests Latest Stable Version codecov.io

HTMLObject 是一套用于创建和操作HTML对象抽象的类。

Anahkiasen/html-object 分支而来

安装

composer require kylekatarnls/html-object

对类进行静态调用

echo Element::p('text')->class('foobar');
// <p class="foobar">text</p>
$list = List::ul(array('foo', 'bar'));

$link = Link::create('#', 'Someone');
$list->getChild(0)->addClass('active')->setValue('by '.$link);
// <ul>
//   <li class="active">foo</li>
//   <li>by <a href="#">Someone</a></li>
// </ul>
echo Link::create('#foo', 'link')->class('btn btn-success')->blank();
// <a href="#foo" class="btn btn-primary" target="_blank">link</a>

扩展核心类

核心类旨在被扩展,并用于创建复杂模式。所有类都实现了如下的树遍历属性:

$element = Element::figure();

$element->nest('content') // <figure>content</figure>

$element->nest('p', 'content') // <figure><p>content</p></figure>

$image = Image::create('img.jpg')->alt('foo'); // <img src="img.jpg" alt="foo" />
$element->setChild($image, 'thumb');

$element->getChild('thumb') // HtmlObject\Image
$element->nest(array(
  'caption' => Element::figcaption()->nest(array(
    'text' => Element::p('foobar'),
  )),
));

$element->getChild('caption.text')->getValue() // foobar
// OR
$element->captionText->getValue() // foobar
$element->captionText->getParent(0) // figure->caption
$element->captionText->getParent(1) // figure

$element->wrap('div') // <div><figure>...</figure></div>
$element->wrapValue('div') // <figure><div>...</div></figure>

你可以在 examples 文件夹中看到示例实现。

属性注入

如果你的类使用旨在添加到最终属性数组中的属性,你可以使用 injectProperties 方法注入它们。比如说你有一个 Link 类,它有一个 url 属性,你可以像这样覆盖方法,然后 $this->url 将被添加到 href 属性中

protected function injectProperties()
{
  return array(
    'href' => $this->url,
  );
}

或者如果属性名称与属性名相同,你可以简单地将其添加到自动注入属性数组中

protected $injectedProperties = array('href', 'title');

// Will be added as href="#foo"
protected $href = '#foo';

// Will be added as title="title"
protected $title = 'title';

修改已创建的树

HtmlObject 允许使用 openclose 打开标签,但是当你的标签有子标签时,有时你希望在特定点打开树以在运行时注入数据,你可以这样做:

$mediaObject = Element::div([
  'title' => Element::h2('John Doe'),
  'body'  => Element::div(),
]);

echo $mediaObject->openOn('body').'My name is John Doe'.$mediaObject->close();
<div>
  <h2>John Doe</h2>
  <div>My name is John Doe</div>
</div>

配置

你可以通过以下方式更改是否遵循xHTML或HTML5规范:

Tag::$config['doctype'] = '{xhtml|html}';