Skip to content

Instantly share code, notes, and snippets.

@tgs
Created November 22, 2013 18:47
Show Gist options
  • Save tgs/7604889 to your computer and use it in GitHub Desktop.
Save tgs/7604889 to your computer and use it in GitHub Desktop.
Convert the specification of allowed tags, attributes, etc. for Python's Bleach module, into a list that CKEditor understands. This is useful because, if you don't tell CKEditor what tags it can use, it will likely use ones you don't want to allow through.
import StringIO
def allowed_content(tags, attributes={}, styles=()):
"""
Given a list of allowed tags, dict of allowed attributes, and list of
allowed styles, generates a CKEditor 'allowedcontent' string. The default
lists used by the bleach module are: bleach.ALLOWED_TAGS,
bleach.ALLOWED_ATTRIBUTES, and bleach.ALLOWED_STYLES (which is empty by
default). This function's defaults are all empty lists/dicts.
CKEditor also allows setting what CSS classes are allowed, but
this function doesn't support that yet.
http://docs.ckeditor.com/#!/guide/dev_allowed_content_rules
>>> allowed_content(['a', 'h1'])
'a;h1;'
>>> allowed_content(['a', 'h1'], {'a': ('href',)})
'a[href];h1;'
>>> allowed_content(['a', 'h1'], styles=('color', 'background-color'))
'a{color,background-color};h1{color,background-color};'
"""
allowed = StringIO.StringIO()
for tag in tags:
allowed.write(tag)
if tag in attributes:
allowed.write('[')
allowed.write(",".join(attributes[tag]))
allowed.write(']')
if styles:
allowed.write('{')
allowed.write(",".join(styles))
allowed.write('}')
allowed.write(';')
return allowed.getvalue()
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment