Draft.js Exporter
draftjs-exporter is a Python library designed to convert rich text from Draft.js raw ContentState, a JSON representation used by the React-based rich text editor, into HTML. It is actively maintained by Springload, currently at version 5.2.0, and regularly releases updates to support newer Python versions and introduce features or performance improvements.
Warnings
- breaking Removed support for older Python versions. v5.0.0+ requires Python 3.6+, v4.0.0+ requires Python 3.5+, v3.0.0+ requires Python 3.4+.
- breaking The default string engine in v4.0.0 removed HTML attributes alphabetical sorting and disabled single/double quotes escaping outside of attributes.
- gotcha The `parse_html` method (available via `DOMEngine` implementations) does not sanitize its input. Directly using user-provided HTML with this method can lead to XSS vulnerabilities.
- gotcha The default 'string' engine is fast and dependency-free but offers no HTML sanitization. For robust handling of potentially unsafe HTML, especially when dealing with user-generated content or arbitrary HTML, consider using the `html5lib` or `lxml` engines.
- gotcha Version 5.0.0 introduced a new `string_compat` engine. If precise, backward-compatible HTML output is critical, this engine is recommended.
Install
-
pip install draftjs-exporter -
pip install draftjs-exporter[html5lib] -
pip install draftjs-exporter[lxml]
Imports
- HTML
from draftjs_exporter.html import HTML
- DOM
from draftjs_exporter.dom import DOM
Quickstart
from draftjs_exporter.dom import DOM
from draftjs_exporter.html import HTML
# Example Draft.js ContentState
content_state = {
'entityMap': {},
'blocks': [
{
'key': '6mgfh',
'text': 'Hello, world!',
'type': 'unstyled',
'depth': 0,
'inlineStyleRanges': [],
'entityRanges': []
}
]
}
# Configuration options (can be customized)
config = {
# Example: use the string_compat engine for consistent output
'engine': DOM.STRING_COMPAT
}
# Initialize the exporter
exporter = HTML(config)
# Render the ContentState to HTML
html_output = exporter.render(content_state)
print(html_output)
# Expected output: '<p>Hello, world!</p>'