Contentful Rich Text Renderer

0.2.8 · active · verified Thu Apr 16

The Contentful Rich Text Renderer is a Python library designed to serialize the RichText field type from Contentful into its corresponding HTML representation by default. It provides flexible rendering capabilities, allowing for full customization of node and mark rendering. It is commonly used alongside the Contentful Delivery SDK. The current version is 0.2.8, and releases are typically tied to updates in the Contentful ecosystem as needed.

Common errors

Warnings

Install

Imports

Quickstart

Initializes `RichTextRenderer` and renders a sample Rich Text JSON document to HTML. It also demonstrates how to provide a custom renderer for specific block types like 'embedded-entry-block' to control how linked entries are displayed.

from rich_text_renderer import RichTextRenderer

# Example Rich Text document (typically obtained from Contentful API)
document = {
    'nodeType': 'document',
    'data': {},
    'content': [
        {
            'nodeType': 'paragraph',
            'data': {},
            'content': [
                {'nodeType': 'text', 'value': 'Hello, ', 'marks': []},
                {'nodeType': 'text', 'value': 'Contentful Rich Text!', 'marks': [{'type': 'bold'}]}
            ]
        }
    ]
}

renderer = RichTextRenderer()
html_output = renderer.render(document)
print(html_output)

# Example with a custom renderer for a specific block type (e.g., 'embedded-entry-block')
from rich_text_renderer.base_node_renderer import BaseNodeRenderer
from rich_text_renderer.base_renderer import BLOCKS

class MyEntryBlockRenderer(BaseNodeRenderer):
    def render(self, node):
        entry_id = node['data']['target']['sys']['id']
        # In a real application, you would fetch entry data using the Contentful SDK
        # For this example, we'll just return a placeholder HTML string.
        return f'<div class="embedded-entry" data-entry-id="{entry_id}">Custom Embedded Entry: {entry_id}</div>'

custom_renderer = RichTextRenderer({
    BLOCKS.EMBEDDED_ENTRY: MyEntryBlockRenderer()
})

document_with_entry = {
    'nodeType': 'document',
    'data': {},
    'content': [
        {
            'nodeType': 'paragraph',
            'data': {},
            'content': [
                {'nodeType': 'text', 'value': 'Here is an ', 'marks': []},
                {'nodeType': 'text', 'value': 'embedded entry:', 'marks': [{'type': 'italic'}]}
            ]
        },
        {
            'nodeType': 'embedded-entry-block',
            'data': {
                'target': {
                    'sys': {'id': 'my-custom-entry', 'type': 'Link', 'linkType': 'Entry'}
                }
            },
            'content': []
        }
    ]
}

html_output_custom = custom_renderer.render(document_with_entry)
print('\n--- With Custom Renderer ---')
print(html_output_custom)

view raw JSON →