Allowing certain attributes on specific HTML elements in CKeditor within Drupal


The CKEditor Drupal Module now has a dedicated configuration for ACF where you can put your Extra allowed content in a text area that is labeled as such!

CKEditor (version 4+) by default does a great job filtering unwanted markup, so it’s highly recommended not to disable the Advanced Content Filter (AFC).

You could create your complete own set of rules to define which tags and attributes to allow in your markup using config.allowedContent, but that is ususally not what you’ll need if you only want to add a little bit more freedom of tags or attributes you can use within CKEditor. That’s where config.extraAllowedContent comes into play: it keeps your default Content Filtering rules and extends them with only the stuff you specify.

In my case I simply needed to allow three class names to be allowed on any <p> tag.

In the Custom Javascript Configuration of my desired CKEditor profile (to be found at admin/config/content/ckeditor/edit/YOUR_PROFILE) I simply added:

config.extraAllowedContent = 'p(btn, medium, default)';

You are also able to use wildcards, so if you want to allow any class to be applied on any tag change the following to:

config.extraAllowedContent = '*(*)';

Parentheses define class rules, curly brackets/braces define inline styles and square brackets define any other attribute. Here’s an example from CKEditor’s official documentation:

// A rule accepting <p> and <h1> elements, but without any property.
p h1

// A rule accepting <p> and <h1> elements with optional "left" and "right" classes.
// Note: Both elements may contain these classes, not only <h1>.
p h1(left,right)

// A rule accepting <p> and <h1> elements with all their attributes.
p h1[*]

// A rule accepting <a> only if it contains the "href" attribute.

// A rule accepting <img> with a required "src" attribute and an optional
// "alt" attribute plus optional "width" and "height" styles.

// The same as above, because the order of properties and their lists is irrelevant and white-spaces are ignored.
img { height, width } [ !src, alt ]

Leave a Reply