This package is abandoned and no longer maintained. The author suggests using the drupol/htmltag package instead.

Generates HTML tags.

dev-master 2017-09-25 18:41 UTC


Build Status Scrutinizer Code Quality Code Coverage Latest Stable Version Total Downloads License



This is a small and extendable PHP library that handle the generation of HTML tags, their attributes and content.



include 'vendor/autoload.php';

$body = \drupol\tagattributes\TagAttributes::tag('body');
//echo $body; // <body/>

// Add content to the body.
$body->content()->set('Body content');
//echo $body; // <body>Body content</body>

// Add some attributes.
$body->attr('class')->set(['alpha', 'beta']);
//echo $body; // <body class="alpha beta">Body content</body>

// Replace the class alpha with something else.
$body->attr('class')->replace('alpha', 'gamma');
//echo $body; // <body class="beta gamma">Body content</body>

// Add more content.
$body->content()->append(' and some more content.');
//echo $body; // <body class="beta gamma">Body content and some more content.</body>

// Create another tag and add it to the body...
$h1 = \drupol\tagattributes\TagAttributes::tag('h1')
  ->content()->set('Hello World!');
$h1->attr('class')->set(['alpha', 'beta']);

// And another one...
$paragraph = \drupol\tagattributes\TagAttributes::tag('p')
  ->content()->set('Lorem ipsum dolor sit amet.');

// And another one...
$button = \drupol\tagattributes\TagAttributes::tag('button')
  ->content()->set('Click me')
  ->attr('class')->set(['java', 'button'])
  ->attr('onclick')->set("alert('You clicked me!');");

// And another one...
$link = \drupol\tagattributes\TagAttributes::tag('a')
  ->content()->set('Go to Google');

// Fix a typo in an attribute...
$button->attr('class')->replace('java', 'javascript');

// Remove and add a class...

// Apply a callback to each class values

// Add nested tags.

echo $body;

// Result:
// <body class="beta gamma">
//   <h1 class="alpha beta" role="title">Hello World!</h1>
//   <p class="INTRO" data-paragraph>Lorem ipsum dolor sit amet.</p>
//   <button class="button javascript" onclick="alert('You clicked me!');" value="clicked">Click me</button>
//   <a href="https://google.com/">Go to Google</a>
// </body>

// Extend the behavior of the library by creating a custom attribute object.
class MyCustomAttribute extends \drupol\tagattributes\Plugins\AttributeBase {
     * {inheritdoc}
    public function prepareValuesBeforeRender(&$values) {
        array_walk($values, function(&$item) {
            $item .= '-extended';

// Register the object in the library.
    'attribute', // Type of plugin to register: tag, attributes or attribute.
    '_default', // Use '_default' for overriding the default behavior or the name of the attribute(value, href,...)
    function($name, $value, $parent) {
        return new MyCustomAttribute($name, $value, $parent);


Feel free to contribute to this library by sending Github pull requests. I'm quite reactive :-)