function markdown_to_html
Converts Markdown formatted text to HTML using the python-markdown library with multiple extensions, falling back to basic conversion if the library is unavailable.
/tf/active/vicechatdev/vice_ai/complex_app.py
1794 - 1819
moderate
Purpose
This function provides a robust Markdown-to-HTML conversion mechanism for web applications. It leverages python-markdown with extensions for tables, fenced code blocks, syntax highlighting, newline-to-break conversion, and table of contents generation. If python-markdown is not available (determined by MARKDOWN_AVAILABLE flag), it falls back to a basic conversion function. This is useful for rendering user-generated Markdown content, documentation, or formatted text in web interfaces.
Source Code
def markdown_to_html(markdown_text):
"""Convert Markdown text to HTML using python-markdown if available"""
if not markdown_text:
return ""
if MARKDOWN_AVAILABLE:
# Use python-markdown with extensions for better conversion
html_content = markdown.markdown(
markdown_text,
extensions=[
'tables',
'fenced_code',
'codehilite',
'nl2br', # Convert newlines to <br>
'toc' # Table of contents
],
extension_configs={
'codehilite': {
'css_class': 'highlight'
}
}
)
return html_content
else:
# Fallback to basic conversion
return basic_markdown_to_html(markdown_text)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
markdown_text |
- | - | positional_or_keyword |
Parameter Details
markdown_text: A string containing Markdown formatted text to be converted to HTML. Can be None or empty string, in which case an empty string is returned. Supports standard Markdown syntax including tables, code blocks, headers, lists, and other formatting elements.
Return Value
Returns a string containing the HTML representation of the input Markdown text. If markdown_text is None or empty, returns an empty string. The HTML includes proper formatting for tables, syntax-highlighted code blocks (with 'highlight' CSS class), converted newlines to <br> tags, and table of contents markup if headers are present. If python-markdown is unavailable, returns the result from basic_markdown_to_html() function.
Dependencies
markdownmarkdown.extensions.tablesmarkdown.extensions.fenced_codemarkdown.extensions.codehilite
Required Imports
import markdown
from markdown.extensions import tables
from markdown.extensions import fenced_code
from markdown.extensions import codehilite
Conditional/Optional Imports
These imports are only needed under specific conditions:
import markdown
Condition: Required when MARKDOWN_AVAILABLE is True for full-featured conversion
Required (conditional)Usage Example
# Assuming MARKDOWN_AVAILABLE is True and basic_markdown_to_html is defined
markdown_text = '''
# Header
This is **bold** and *italic* text.
## Code Example
python
def hello():
print("Hello, World!")
| Column 1 | Column 2 |
|----------|----------|
| Data 1 | Data 2 |
'''
html_output = markdown_to_html(markdown_text)
print(html_output)
# Output: '<h1>Header</h1>\n<p>This is <strong>bold</strong> and <em>italic</em> text.</p>...'
# Handle empty input
empty_result = markdown_to_html(None)
print(empty_result) # Output: ''
# Handle empty string
empty_result = markdown_to_html('')
print(empty_result) # Output: ''
Best Practices
- Ensure MARKDOWN_AVAILABLE flag is properly set at module initialization to avoid runtime errors
- Always validate or sanitize the HTML output if displaying user-generated content to prevent XSS attacks
- Define CSS styles for the 'highlight' class to properly display syntax-highlighted code blocks
- Implement the basic_markdown_to_html() fallback function to handle cases where python-markdown is not installed
- Consider caching converted HTML for frequently accessed Markdown content to improve performance
- The function returns empty string for None/empty input, so no additional null checks are needed by callers
- Be aware that the 'nl2br' extension converts all newlines to <br> tags, which may affect formatting in some contexts
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function basic_markdown_to_html 78.4% similar
-
function simple_markdown_to_html 76.0% similar
-
function html_to_markdown 75.4% similar
-
function html_to_markdown_v1 74.9% similar
-
function convert_markdown_to_html 73.1% similar