generated from hjess/PythonTemplateProject
Lets make the frontpage in markdown too
Some checks failed
Build, Push, and Deploy to Nomad / docker-nomad (push) Has been cancelled
Some checks failed
Build, Push, and Deploy to Nomad / docker-nomad (push) Has been cancelled
This commit is contained in:
@@ -1,123 +1,168 @@
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import markdown
|
||||
from fastapi import FastAPI
|
||||
from jinja2 import Environment, DictLoader
|
||||
from .image_controller import ImageHandler
|
||||
# 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" loading="lazy">
|
||||
<div class="overlay-text">Overlay Text</div>
|
||||
</div>
|
||||
'''
|
||||
from markupsafe import Markup
|
||||
from .image_service import ImageService
|
||||
|
||||
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 link_to(title, url):
|
||||
"""Render a box component."""
|
||||
return f'''
|
||||
<a href="{url}" target="_blank" rel="noopener noreferrer">{title}</a>
|
||||
'''
|
||||
|
||||
def warning(content):
|
||||
"""Render a warning component."""
|
||||
return f'''
|
||||
<div class="warning">
|
||||
⚠️ <p>{content}</p>
|
||||
</div>
|
||||
'''
|
||||
class MarkdownRenderer:
|
||||
def __init__(self, file_path: str = None, app: FastAPI=None):
|
||||
"""
|
||||
Initialize the MarkdownRenderer with a Jinja2 environment and custom functions.
|
||||
"""
|
||||
self.app = app
|
||||
self.image_service = ImageService(self.app)
|
||||
self.jinja_env = self._create_jinja_environment()
|
||||
self.file_path = file_path
|
||||
|
||||
|
||||
def slider(options, images):
|
||||
"""Render a slider using the provided HTML structure."""
|
||||
import uuid
|
||||
modal_id = uuid.uuid4().hex.upper()[0:6] # Lets create some uniq modals
|
||||
|
||||
width = options.get("width", 500)
|
||||
height = options.get("height", 375)
|
||||
def _create_jinja_environment(self) -> Environment:
|
||||
"""
|
||||
Create and configure the Jinja2 environment with custom functions.
|
||||
|
||||
html_content = []
|
||||
html_content.append('<div class="button-stack">')
|
||||
for i, val in enumerate(images):
|
||||
modal_id = f"{modal_id}_{i}"
|
||||
modal_id_next = f"{modal_id}_{i+1}"
|
||||
|
||||
if int(len(images))<=int(i+1):
|
||||
modal_id_next = f"{modal_id}_0"
|
||||
if i % 2 == 0:
|
||||
html_content.append(f"""<button onclick="openModal('modal{modal_id}')" class="stacked-button"> <img src="{val}" alt="Lets do better" class="thumbnail" loading="lazy"></button>""".strip())
|
||||
else:
|
||||
html_content.append(f"""<button onclick="openModal('modal{modal_id}')" class="stacked-button"> <img src="{val}" alt="Lets do better" class="thumbnail" loading="lazy"></button>""".strip())
|
||||
html_content.append(f"""<div class="modal" id="modal{modal_id}">
|
||||
<div class="modal-content">
|
||||
<h2>Modal {i}</h2>
|
||||
<img src="{val}" alt="Lets do better" loading="lazy">
|
||||
<div class="modal-buttons">
|
||||
<button onclick="closeModal('modal{modal_id}')">Close</button>
|
||||
<button class="next-btn" onclick="nextModal('modal{modal_id}', 'modal{modal_id_next}')">Next</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>""")
|
||||
Returns:
|
||||
Environment: A configured Jinja2 environment.
|
||||
"""
|
||||
env = Environment(loader=DictLoader({"base_template": "{{ content | safe }}"}))
|
||||
|
||||
html_content.append( '</div>' )
|
||||
html = '\n'.join( html_content )
|
||||
env.globals.update({
|
||||
"img_left_overlay": self.img_left_overlay,
|
||||
"box": self.box,
|
||||
"note": self.note,
|
||||
"warning": self.warning,
|
||||
"link_to": self.link_to,
|
||||
"slider": self.slider,
|
||||
"image": self.get_image, # Add image handler function
|
||||
})
|
||||
return env
|
||||
|
||||
return html
|
||||
def img_left_overlay(self, src: str) -> str:
|
||||
"""Render an image with overlay."""
|
||||
return f'''
|
||||
<div class="img-left-overlay">
|
||||
<img src="{src}" alt="Overlay Image" loading="lazy">
|
||||
<div class="overlay-text">Overlay Text</div>
|
||||
</div>
|
||||
'''
|
||||
|
||||
def box(self, title: str, content: str) -> str:
|
||||
"""Render a box component."""
|
||||
return f'''
|
||||
<div class="box">
|
||||
<strong>{title}</strong>
|
||||
<p>{content}</p>
|
||||
</div>
|
||||
'''
|
||||
|
||||
def note(self, content: str) -> str:
|
||||
"""Render a note component."""
|
||||
return f'''
|
||||
<div class="note">
|
||||
<p>{content}</p>
|
||||
</div>
|
||||
'''
|
||||
|
||||
def link_to(self, title: str, url: str) -> str:
|
||||
"""Render a link component."""
|
||||
return f'''
|
||||
<a href="{url}" target="_blank" rel="noopener noreferrer">{title}</a>
|
||||
'''
|
||||
|
||||
def warning(self, content: str) -> str:
|
||||
"""Render a warning component."""
|
||||
return f'''
|
||||
<div class="warning">
|
||||
⚠️ <p>{content}</p>
|
||||
</div>
|
||||
'''
|
||||
|
||||
def slider(self, options: dict, images: list) -> str:
|
||||
"""Render a slider component."""
|
||||
import uuid
|
||||
modal_id = uuid.uuid4().hex.upper()[0:6]
|
||||
|
||||
|
||||
def create_jinja_environment():
|
||||
"""Create and configure the Jinja2 environment."""
|
||||
env = Environment(loader=DictLoader({"base_template": "{{ content | safe }}"}))
|
||||
image_handler = ImageHandler(base_dir="static/images")
|
||||
html_content = []
|
||||
html_content.append('<div class="button-stack">')
|
||||
for i, val in enumerate(images):
|
||||
self.image_service = ImageService( self.app )
|
||||
print(val)
|
||||
modal_id_current = f"{modal_id}_{i}"
|
||||
modal_id_next = f"{modal_id}_{i + 1}" if i + 1 < len(images) else f"{modal_id}_0"
|
||||
|
||||
env.globals.update({
|
||||
"img_left_overlay": img_left_overlay,
|
||||
"box": box,
|
||||
"note": note,
|
||||
"warning": warning,
|
||||
"link_to": link_to,
|
||||
"slider": slider,
|
||||
"image": image_handler.generate_image_tag, # Add image handler function
|
||||
html_content.append(f"""
|
||||
<button onclick="openModal('modal{modal_id_current}')" class="stacked-button">
|
||||
<img src="{val}" alt="Image {i}" class="thumbnail" loading="lazy">
|
||||
</button>
|
||||
<div class="modal" id="modal{modal_id_current}">
|
||||
<div class="modal-content">
|
||||
<h2>Modal {i}</h2>
|
||||
<img src="{val}" alt="Image {i}" loading="lazy">
|
||||
|
||||
<div class="modal-buttons">
|
||||
<button onclick="closeModal('modal{modal_id_current}')">Close</button>
|
||||
<button class="next-btn" onclick="nextModal('modal{modal_id_current}', 'modal{modal_id_next}')">Next</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
""")
|
||||
html_content.append('</div>')
|
||||
return '\n'.join(html_content)
|
||||
|
||||
})
|
||||
return env
|
||||
def _get_category(self):
|
||||
if isinstance(self.file_path, str):
|
||||
this_path = Path(self.file_path)
|
||||
return this_path.parent.name
|
||||
|
||||
def render_markdown_with_jinja(markdown_content: str):
|
||||
"""
|
||||
Convert Markdown to HTML and apply Jinja2 rendering for custom tags.
|
||||
return True
|
||||
|
||||
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"])
|
||||
intermediate_html = md.convert(markdown_content)
|
||||
metadata = {key: " ".join(value) for key, value in md.Meta.items()} if md.Meta else {}
|
||||
def get_image(self, image_type: str, filename: str, alt: str = "", width: int = None, height: int = None) -> Markup:
|
||||
"""
|
||||
Generate a dynamic HTML <img> tag for an image using ImageService's image_tag method.
|
||||
"""
|
||||
valid_types = ['thumbnails', 'large', 'small', 'original']
|
||||
if image_type not in valid_types:
|
||||
sys.tracebacklimit = 0
|
||||
raise ValueError( f"Invalid image type: {image_type}. Must be one of {valid_types}" )
|
||||
|
||||
# Step 2: Pass the resulting HTML with Jinja2 custom tags through Jinja2
|
||||
env = create_jinja_environment()
|
||||
tag = self.image_service.image_tag(
|
||||
category=self._get_category(),
|
||||
image_type=image_type,
|
||||
filename=filename,
|
||||
alt=alt,
|
||||
width=width,
|
||||
height=height
|
||||
)
|
||||
my_tag = Markup(tag)
|
||||
print(my_tag)
|
||||
return my_tag
|
||||
|
||||
template = env.get_template("base_template")
|
||||
final_html = template.render(content=intermediate_html)
|
||||
|
||||
# Step 3: Re-render final_html in Jinja2 for embedded tags like {{ image(...) }}
|
||||
final_output = env.from_string(final_html).render()
|
||||
|
||||
return final_output, metadata
|
||||
|
||||
def render_markdown_with_jinja(self, 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.
|
||||
"""
|
||||
|
||||
md = markdown.Markdown(extensions=["extra", "nl2br", "meta"])
|
||||
intermediate_html = md.convert(markdown_content)
|
||||
metadata = {key: " ".join(value) for key, value in md.Meta.items()} if md.Meta else {}
|
||||
|
||||
# Step 3: Pass the resulting HTML with Jinja2 custom tags through Jinja2
|
||||
template = self.jinja_env.get_template("base_template")
|
||||
final_html = template.render(content=intermediate_html)
|
||||
|
||||
# Step 4: Re-render final_html in Jinja2 for embedded tags like {{ image(...) }}
|
||||
final_output = self.jinja_env.from_string(final_html).render()
|
||||
|
||||
return final_output, metadata
|
||||
Reference in New Issue
Block a user