🔍 Code Extractor

function convert_quill_delta_to_html

Maturity: 44

Converts Quill Delta format (rich text editor format) to HTML, with fallback handling for plain text, JSON strings, and already-formatted HTML content.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
3505 - 3533
Complexity:
moderate

Purpose

This function serves as a robust converter for Quill Delta format content to HTML. It handles multiple input formats: Quill Delta JSON objects, JSON strings containing Delta operations, plain HTML strings, and plain text. It's designed to be fault-tolerant with multiple fallback mechanisms, making it suitable for processing user-generated content from Quill-based rich text editors in web applications. The function is particularly useful in document management systems where content may be stored in various formats and needs to be rendered as HTML.

Source Code

def convert_quill_delta_to_html(content):
    """Convert Quill Delta format to HTML"""
    if not content:
        return ""
    
    try:
        # Check if content is already HTML
        if isinstance(content, str) and ('<' in content and '>' in content):
            return content
        
        # Check if content is Quill Delta JSON
        if isinstance(content, str):
            try:
                delta = json.loads(content)
                if 'ops' in delta:
                    return delta_to_html(delta['ops'])
            except json.JSONDecodeError:
                # Not JSON, treat as plain text
                return f"<p>{content}</p>"
        
        elif isinstance(content, dict) and 'ops' in content:
            return delta_to_html(content['ops'])
        
        # Fallback to string content
        return f"<p>{str(content)}</p>"
        
    except Exception as e:
        logger.warning(f"Error converting Quill Delta: {e}")
        return f"<p>{str(content)}</p>"

Parameters

Name Type Default Kind
content - - positional_or_keyword

Parameter Details

content: The content to convert. Can be: (1) A Quill Delta dictionary with 'ops' key containing operations array, (2) A JSON string representing Quill Delta format, (3) An HTML string (returned as-is), (4) Plain text string (wrapped in <p> tags), or (5) None/empty value (returns empty string). The function intelligently detects the format and processes accordingly.

Return Value

Returns a string containing HTML markup. If input is valid Quill Delta, returns formatted HTML from delta_to_html() function. If input is already HTML, returns it unchanged. For plain text, returns text wrapped in <p> tags. On error or invalid input, returns content wrapped in <p> tags as fallback. Returns empty string if content is None or empty.

Dependencies

  • json
  • logging

Required Imports

import json
import logging

Usage Example

import json
import logging

logger = logging.getLogger(__name__)

# Define or import delta_to_html function
def delta_to_html(ops):
    # Implementation to convert ops to HTML
    html_parts = []
    for op in ops:
        if 'insert' in op:
            html_parts.append(str(op['insert']))
    return ''.join(html_parts)

# Example 1: Quill Delta as dictionary
delta_dict = {'ops': [{'insert': 'Hello World'}]}
html_output = convert_quill_delta_to_html(delta_dict)
print(html_output)  # Output from delta_to_html

# Example 2: Quill Delta as JSON string
delta_json = '{"ops": [{"insert": "Hello World"}]}'
html_output = convert_quill_delta_to_html(delta_json)
print(html_output)

# Example 3: Plain text
plain_text = 'Simple text'
html_output = convert_quill_delta_to_html(plain_text)
print(html_output)  # <p>Simple text</p>

# Example 4: Already HTML
html_input = '<div>Already HTML</div>'
html_output = convert_quill_delta_to_html(html_input)
print(html_output)  # <div>Already HTML</div>

# Example 5: Empty content
html_output = convert_quill_delta_to_html(None)
print(html_output)  # ''

Best Practices

  • Ensure the 'delta_to_html' function is properly defined or imported before using this function
  • Initialize a logger object in the module scope to capture conversion warnings
  • The function is designed to never raise exceptions - it always returns a string, making it safe for use in templates and APIs
  • When passing Quill Delta content, ensure it follows the standard format with an 'ops' key containing an array of operations
  • The function performs simple HTML detection using '<' and '>' characters - for more robust HTML detection, consider enhancing this logic
  • Consider sanitizing the output HTML if it will be rendered in a web context to prevent XSS attacks
  • The function wraps plain text in <p> tags - ensure this behavior aligns with your application's HTML structure requirements

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function delta_to_html 92.5% similar

    Converts Quill Delta operations (rich text format) to HTML markup while preserving the order and structure of formatted text, headers, lists, and inline styles.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function html_to_markdown 60.4% similar

    Converts HTML text back to Markdown format using regex-based pattern matching and replacement, handling headers, code blocks, formatting, links, lists, and HTML entities.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function export_to_docx 60.3% similar

    Exports a document with text and data sections to Microsoft Word DOCX format, preserving formatting, structure, and metadata.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function html_to_markdown_v1 60.2% similar

    Converts HTML markup to Markdown syntax, handling headers, code blocks, text formatting, links, lists, and paragraphs with proper spacing.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function simple_markdown_to_html 58.9% similar

    Converts a subset of Markdown syntax to clean HTML, supporting headers, bold text, unordered lists, and paragraphs.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
← Back to Browse