anahkiasenplus/html-object

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

dev-master 2018-10-29 04:10 UTC

This package is not auto-updated.

Last update: 2024-09-25 09:41:59 UTC


README

Build Status Latest Stable Version Total Downloads Scrutinizer Quality Score Code Coverage Support via Gittip

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

对类进行静态调用

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方法注入它们。假设您有一个具有url属性的Link类,您可以像这样覆盖方法,并将$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}';