kylerkatarnls / html-object
一套用于创建和操作HTML对象抽象的类
资助包维护!
kylerkatarnls
Open Collective
Tidelift
Requires
- php: >=5.3.0
Requires (Dev)
- madewithlove/php-cs-fixer-config: ^1.3
- phpunit/phpunit: ^4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.32 || ^9.6.3 || ^10.0.11
- phpunit/phpunit-dom-assertions: ^0.1.0 || ^2.6.0
- symfony/css-selector: ^2.6 || ^4.4.27 || ^5.4.0 || ^6.0.0
Replaces
- anahkiasen/html-object: 1.5.2
README
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 允许使用 open
和 close
打开标签,但是当你的标签有子标签时,有时你希望在特定点打开树以在运行时注入数据,你可以这样做:
$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}';