generated from hjess/PythonTemplateProject
Lets test
This commit is contained in:
70
app/services/markdown_render.py
Normal file
70
app/services/markdown_render.py
Normal file
@@ -0,0 +1,70 @@
|
||||
import markdown
|
||||
from jinja2 import Environment, DictLoader
|
||||
|
||||
# Define Jinja2 custom functions
|
||||
def img_left_overlay(src):
|
||||
"""Render an image with overlay."""
|
||||
return f'''
|
||||
<div class="img-left-overlay">
|
||||
<img src="{src}" alt="Overlay Image">
|
||||
<div class="overlay-text">Overlay Text</div>
|
||||
</div>
|
||||
'''
|
||||
|
||||
def box(title, content):
|
||||
"""Render a box component."""
|
||||
return f'''
|
||||
<div class="box">
|
||||
<strong>{title}</strong>
|
||||
<p>{content}</p>
|
||||
</div>
|
||||
'''
|
||||
|
||||
def note(content):
|
||||
"""Render a note component."""
|
||||
return f'''
|
||||
<div class="note">
|
||||
<p>{content}</p>
|
||||
</div>
|
||||
'''
|
||||
|
||||
def warning(content):
|
||||
"""Render a warning component."""
|
||||
return f'''
|
||||
<div class="warning">
|
||||
⚠️ <p>{content}</p>
|
||||
</div>
|
||||
'''
|
||||
|
||||
def create_jinja_environment():
|
||||
"""Set up Jinja2 environment and register custom components."""
|
||||
env = Environment(loader=DictLoader({"base_template": "{{ content | safe }}"}))
|
||||
env.globals.update({
|
||||
"img_left_overlay": img_left_overlay,
|
||||
"box": box,
|
||||
"note": note,
|
||||
"warning": warning,
|
||||
})
|
||||
return env
|
||||
|
||||
def render_markdown_with_jinja(markdown_content: str):
|
||||
"""
|
||||
Convert Markdown to HTML and apply Jinja2 rendering for custom tags.
|
||||
|
||||
Args:
|
||||
markdown_content (str): Raw Markdown content.
|
||||
|
||||
Returns:
|
||||
tuple: Rendered HTML content and metadata as a dictionary.
|
||||
"""
|
||||
# Step 1: Convert Markdown to HTML and extract metadata
|
||||
md = markdown.Markdown(extensions=["extra", "nl2br", "meta"])
|
||||
html_content = md.convert(markdown_content)
|
||||
metadata = {key: " ".join(value) for key, value in md.Meta.items()} if md.Meta else {}
|
||||
|
||||
# Step 2: Render the HTML with Jinja2 to apply custom tags
|
||||
env = create_jinja_environment()
|
||||
template = env.get_template("base_template")
|
||||
final_html = template.render(content=html_content)
|
||||
|
||||
return final_html, metadata
|
||||
Reference in New Issue
Block a user