Allowing HTML Purifier to accept the details and summary tags.


The HTML Purifier library is a great way to filter user-supplied HTML, normally from WYSIWYG Rich Text editors, and remove potentially malicious content. It can also be used to ensure that certain elements always get saved with particular attribues. Ie, ensuring any user-supplied link has target="_blank" and rel="nofollow". Depending on your use case, you may even want to prevent users from inserting non HTTPS links etc.

One downside to using a library for this, is if you want to use a newer HTML elements, such as details and summary, the library may not yet know about them! This is currently the case with HTML Purifier and these tags. Most browsers support the, with IE and Edge being the main exceptions.

These tags allow a really simple pure HTML only way of having an expandable section on your page. Here’s an example.

Now that we know what these tags elements are, let’s look at how to implement them in HTML Purifier.

$config = \HTMLPurifier_Config::createDefault();
# Other configuration options you may use
$def = $config->getHTMLDefinition(true);
$def->addElement(
    'details',
    'Block',
    'Flow',
    'Common',
    array(
        'open' => new \HTMLPurifier_AttrDef_HTML_Bool(true)
    )
);
$def->addElement('summary', 'Inline', 'Inline', 'Common');

It’s not super-obvious when reading their docs, at least it wasn’t for myself, but you need to use new \HTMLPurifier_AttrDef_HTML_Bool(true) for the 'open' element. Simply using 'open' => 'Bool' doesn’t work, neither does 'open' => new \HTMLPurifier_AttrDef_HTML_Bool().

Hopefully this will make it easier for someone else out there to add these super-cool elements into their list of allowed elements.