将富文本从Draft.js原始ContentState转换为HTML的库

draftjs-exporter的Python项目详细描述


draft.js exporterpypitravis工作服

< Buff行情>

将富文本从draft.js原始内容状态转换为HTML的库。

它与富文本编辑器一起开发,用于wagtail。查看在线演示和我们的介绍性博客文章。

为什么

draft.js是一个富文本编辑器框架,用于react。它的方法不同于大多数富文本编辑器,因为它不将数据存储为html,而是以自己的称为contentstate的表示形式存储。当必须在python生态系统中完成contentstate到html的转换时,此导出程序非常有用。

最初的用例是获得对wagtail/django站点中由富文本编辑器管理的内容的更多控制。如果您想阅读全文,请查看我们的博客文章:使用draft.js重新思考富文本管道

功能

该项目遵循语义版本控制,并衡量性能和性能。波特" rel="nofollow">代码覆盖范围

  • 生成的HTML的广泛配置。
  • 常用HTML元素的默认可扩展块内联样式映射。
  • 将换行符转换为<;br>;元素。
  • 在块映射中定义任何属性–元素的自定义类名。
  • 像api一样反应以创建自定义组件。
  • 自动将实体数据转换为HTML属性(从Int&Boolean转换为字符串,从Style对象转换为Style字符串)。
  • 嵌套列表(<;li>;元素位于<;ul>;<;ol>;内部,具有多个级别)。
  • 将内联样式输出为内联元素(<;em>;<;strong>;,选择并选择任何属性)。
  • 重叠的内联样式和实体范围。

用法

js将数据存储在基于块的js on表示中,表示编辑器中的内容行,并用实体和样式进行注释以表示富文本。有关更多信息,本文将进一步介绍这些概念。

入门

这个导出器将draft.js contentstate数据作为输入,并基于其co输出html配置。要开始,请安装软件包:

pip install draftjs_exporter

在代码中,创建导出器并使用render方法创建html:

fromdraftjs_exporter.domimportDOMfromdraftjs_exporter.htmlimportHTML# Configuration options are detailed below.config={}# Initialise the exporter.exporter=HTML(config)# Render a Draft.js `contentState`html=exporter.render({'entityMap':{},'blocks':[{'key':'6mgfh','text':'Hello, world!','type':'unstyled','depth':0,'inlineStyleRanges':[],'entityRanges':[]}]})print(html)

您还可以通过下载此存储库,然后使用python example.py,或者使用我们的联机Draft.js演示来运行示例

配置

导出器输出可广泛配置,以满足各种富文本要求。

# draftjs_exporter provides default configurations and predefined constants for reuse.fromdraftjs_exporter.constantsimportBLOCK_TYPES,ENTITY_TYPESfromdraftjs_exporter.defaultsimportBLOCK_MAP,STYLE_MAPfromdraftjs_exporter.domimportDOMconfig={# `block_map` is a mapping from Draft.js block types to a definition of their HTML representation.# Extend BLOCK_MAP to start with sane defaults, or make your own from scratch.'block_map':dict(BLOCK_MAP,**{# The most basic mapping format, block type to tag name.BLOCK_TYPES.HEADER_TWO:'h2',# Use a dict to define props on the block.BLOCK_TYPES.HEADER_THREE:{'element':'h3','props':{'class':'u-text-center'}},# Add a wrapper (and wrapper_props) to wrap adjacent blocks.BLOCK_TYPES.UNORDERED_LIST_ITEM:{'element':'li','wrapper':'ul','wrapper_props':{'class':'bullet-list'},},# Use a custom component for more flexibility (reading block data or depth).BLOCK_TYPES.BLOCKQUOTE:blockquote,BLOCK_TYPES.ORDERED_LIST_ITEM:{'element':list_item,'wrapper':ordered_list,},# Provide a fallback component (advanced).BLOCK_TYPES.FALLBACK:block_fallback}),# `style_map` defines the HTML representation of inline elements.# Extend STYLE_MAP to start with sane defaults, or make your own from scratch.'style_map':dict(STYLE_MAP,**{# Use the same mapping format as in the `block_map`.'KBD':'kbd',# The `style` prop can be defined as a dict, that will automatically be converted to a string.'HIGHLIGHT':{'element':'strong','props':{'style':{'textDecoration':'underline'}}},# Provide a fallback component (advanced).INLINE_STYLES.FALLBACK:style_fallback,}),'entity_decorators':{# Map entities to components so they can be rendered with their data.ENTITY_TYPES.IMAGE:image,ENTITY_TYPES.LINK:link# Lambdas work too.ENTITY_TYPES.HORIZONTAL_RULE:lambdaprops:DOM.create_element('hr'),# Discard those entities.ENTITY_TYPES.EMBED:None,# Provide a fallback component (advanced).ENTITY_TYPES.FALLBACK:entity_fallback,},'composite_decorators':[# Use composite decorators to replace text based on a regular expression.{'strategy':re.compile(r'\n'),'component':br,},{'strategy':re.compile(r'#\w+'),'component':hashtag,},{'strategy':LINKIFY_RE,'component':linkify,},],}

有关详细信息,请参见examples.py

高级用法

自定义组件

为了使用动态数据生成任意标记,导出器附带了一个api来创建呈现组件。这个api镜像了react的createelement(jsx编译的内容)api。

# All of the API is available from a single `DOM` namespacefromdraftjs_exporter.domimportDOM# Components are simple functions that take `props` as parameter and return DOM elements.defimage(props):# This component creates an image element, with the relevant attributes.returnDOM.create_element('img',{'src':props.get('src'),'width':props.get('width'),'height':props.get('height'),'alt':props.get('alt'),})defblockquote(props):# This component uses block data to render a blockquote.block_data=props['block']['data']# Here, we want to display the block's content so we pass the `children` prop as the last parameter.returnDOM.create_element('blockquote',{'cite':block_data.get('cite')},props['children'])defbutton(props):href=props.get('href','#')icon_name=props.get('icon',None)text=props.get('text','')returnDOM.create_element('a',{'class':'icon-text'ificon_nameelseNone,'href':href,},# There can be as many `children` as required.# It is also possible to reuse other components and render them instead of HTML tags.DOM.create_element(icon,{'name':icon_name})ificon_nameelseNone,DOM.create_element('span',{'class':'icon-text'},text)ificon_nameelsetext)

除了create_element之外,还可以使用parse_html方法。使用它与其他HTML生成器(如模板引擎)进行交互。

有关详细信息,请参见存储库中的examples.py

后备组件

在处理内容架构中的更改时,作为正在进行的开发或迁移的一部分,某些内容可能会过时。 要解决此问题,导出器允许为块、样式和实体定义回退组件。 此功能目前仅用于开发,如果您在生产中有此功能的用例,我们将很高兴收到您的来信。 请与我们联系!

将以下内容添加到导出器配置中,

config={'block_map':dict(BLOCK_MAP,**{# Provide a fallback for block types.BLOCK_TYPES.FALLBACK:block_fallback}),}

此回退组件现在可以在找不到正常组件时控制导出器行为。下面是一个示例:

defblock_fallback(props):type_=props['block']['type']iftype_=='example-discard':logging.warn('Missing config for "%s". Discarding block, keeping content.'%type_)# Directly return the block's children to keep its content.returnprops['children']eliftype_=='example-delete':logging.error('Missing config for "%s". Deleting block.'%type_)# Return None to not render anything, removing the whole block.returnNoneelse:logging.warn('Missing config for "%s". Using div instead.'%type_)# Provide a fallback.returnDOM.create_element('div',{},props['children'])

有关详细信息,请参见存储库中的examples.py

备用备用发动机

默认情况下,导出器使用名为string的无依赖项引擎来构建dom树。有两种备用引擎:html5lib(通过beautifulsoup)和lxml

字符串引擎是最快的,并且没有任何依赖项。它唯一的缺点是parse嫒html方法不像其他引擎那样对html进行转义/清理。

  • 对于html5lib,请执行pip install draftjs_exporter[html5lib]
  • 对于lxml,请执行pip install draftjs_exporter[lxml]。它还要求系统上提供libxml2libxslt

然后,使用导出器配置的引擎属性:

config={# Specify which DOM backing engine to use.'engine':DOM.HTML5LIB,# Or for lxml:'engine':DOM.LXML,}

定制倒车发动机

导出器支持使用自定义引擎通过domapi生成输出。 此功能目前仅用于开发,如果您在生产中有此功能的用例,我们将很高兴收到您的来信。请与我们联系!

下面是一个实现示例:

fromdraftjs_exporterimportDOMEngineclassDOMListTree(DOMEngine):"""    Element tree using nested lists.    """@staticmethoddefcreate_tag(t,attr=None):return[t,attr,[]]@staticmethoddefappend_child(elt,child):elt[2].append(child)@staticmethoddefrender(elt):returneltexporter=HTML({# Use the dotted module syntax to point to the DOMEngine implementation.'engine':'myproject.example.DOMListTree'})

贡献

看到你喜欢的东西了吗?有什么遗漏吗?我们欢迎所有的支持,无论是关于bug报告、特性请求、代码、设计、审查、测试、文档等等。请查看我们的贡献指南。

如果您只想在自己的计算机上设置项目,贡献指南还包含所有设置命令。

学分

这个项目是由新西兰数字机构springload的工作实现的。漂亮的演示站点是@thibaudcolas的作品

查看贡献者的完整列表。mit许可。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java使用唯一的按钮标签单击按钮   代码生成如何使用Java codeModel为数组的特定索引赋值   java如何批量执行Camel SQL插入   java iText 7将ltv添加到现有签名   内存管理Java应用程序突然停止几天后(810)   带MySQL的java注册表单JavaFX在intellij中失败   如何使用eclipse为windows azure java项目启用远程调试   一种通用的java输入输出设计模式   java Android XML(RSS)忽略引号(“”)   java帮助:安卓中的8 X 10 2维按钮数组   java启动Android项目   JWrapper构建java应用程序   java如何在Android应用程序中设置基于日期/时间的默认页面加载?   java循环程序在完成后返回到起点   java Hibernate:更好的整体类还是多类映射?   回溯数独解算器的递归问题[Java]   java查找类用法   java如何在SpringWebFlow中将多个模型绑定到一个视图?