Skip to content

Instantly share code, notes, and snippets.

@alganet
Created August 10, 2011 22:43
Show Gist options
  • Save alganet/1138479 to your computer and use it in GitHub Desktop.
Save alganet/1138479 to your computer and use it in GitHub Desktop.
HTML generator prototype
<?php
print
h::html(
h::head(
h::title('Hi!')
),
h::body(
h::h1('Hello')->id('oi'),
h::ul(
h::li('foo'),
h::li('bar'),
h::li('baz')
),
h::input()->type('text')->name('username')->value('')
)
);
/* Output Sample:
<html>
<head>
<title>Hi!</title>
</head>
<body>
<h1 id="oi">Hello</h1>
<ul>
<li>foo</li>
<li>bar</li>
<li>baz</li>
</ul>
<input type="text" name="username" value="" />
</body>
</html>
*/
class h {
protected $nodeName = '';
protected $childrenNodes = array();
protected $attributes = array();
public static function __callStatic($name, array $children)
{
return new static($name, $children);
}
public function __construct($name, array $children)
{
$this->nodeName = $name;
$this->childrenNodes = $children;
}
public function __call($attribute, $value)
{
$this->attributes[$attribute] = $value[0];
return $this;
}
public function __toString()
{
$children = implode($this->childrenNodes);
$attrs = $this->renderAttributes();
return count($this->childrenNodes)
? "<{$this->nodeName}{$attrs}>$children</{$this->nodeName}>"
: "<{$this->nodeName}{$attrs} />";
}
protected function renderAttributes()
{
$attrs = '';
foreach ($this->attributes as $attr => &$value)
$attrs .= " $attr=\"$value\"";
return $attrs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment