dmptrluke / django-markdownfield

A simple custom field for Django that can safely render Markdown and store it in the database.
MIT License
44 stars 13 forks source link

Allow CSS Sanitizer to be used when rendering markdown to HTML #16

Closed kirsinger closed 1 year ago

kirsinger commented 1 year ago

Bleach supports validation of CSS via a css_validator kwarg that gets passed to the Cleaner class on initialization. This is useful if you're extending the Python markdown package to support custom syntax that makes use of the style attribute to render correctly.

As an example markdown doesn't support underlined text by default, however some text editing frameworks like draft.js do support underlined text via custom syntax (draft.js uses ++). Rendering this correctly requires writing an extension for the Python markdown module that converts the custom markdown syntax to the corresponding HTML (in this case a span with the style attribute set to text-decoration: underline). Such extensions will often lean on the style attribute to decorate the rendered text, however the way bleach is currently configured means that the value of all style attributes are stripped when the markdown is sanitized.

This PR allows a css_sanitizer to be set on the Validator that's passed to MarkdownField. This defaults to None, which retains the current behavior (ie: the value of all style attributes will be stripped). This behavior can be customized by passing an instance of the CSSSanitizer class to the Validator, which can be used to control which CSS attributes are retained in the rendered HTML.

benjaoming commented 1 year ago

This is great! I'm opting to bump to 0.11 for the next release, though, but I think that's great for other purposes, too :)

CC: @dmptrluke