Purifier with Bootstrap attributes

By default, even using the HTML5 parser, Bootstrap elements are being stripped.

To solve this, edit MY_html_helper.php and add this just before $purifier = new \HTMLPurifier($purifier_config);

$def = $purifier_config->maybeGetRawHTMLDefinition();
if ($def) {
   $def->addAttribute('a', 'data-toggle', 'CDATA');
   $def->addAttribute('ul', 'role', 'CDATA');
   $def->addAttribute('ol', 'role', 'CDATA');
   $def->addAttribute('li', 'role', 'CDATA');
}

$purifier = new \HTMLPurifier($purifier_config);

Then in the purifier.php config, update the HTML.Allowed stanza to include the attribute you want to allow
'HTML.Allowed' => 'div[id|class],b,strong,i[class],em,a[href|title|target],ul[class|role],ol[class|role],li[class|role],p[style|class],br,span[style],img[width|height|alt|src],iframe[src|name|width|height|class|allow]',

My $defs will need to be built up to include all the desired attributes but this is a start.

Perhaps we can improve this by creating an attribute array config item that MY_html_helper looks for and processes? That way we're just editing the config rather than the system files?

Comments

  • Could you provide the HTML string you were trying to save?

  • Here's part of the standard bootstrap notation for a set of tabs

    <ul class="nav nav-tabs">
        <li class="active"><a href="#tab1" data-toggle="tab">Tab 1</a></li>
        <li><a href="#tab2" data-toggle="tab">Tab 2</a></li>
    </ul>
    

    Purifier removes data-toggle="tab" in our setup.

    "data" attributes are well documented in the HTMLpurifier support groups as not being supported out of the box. Along with whole bunches of HTML5 tags. In the official docs, there's a whole section on how to add unsupported tags and attributes - it's not an uncommon experience.

  • Thanks for the example. I've posted an update to allow for specifying custom attributes in the purifier config as well as determining where and if to cache the definition attributes. Test it out and let me know if that helps out.

Sign In or Register to comment.