1
Fork 0
mkdocs-site/hooks/unsplash.py

29 lines
759 B
Python
Raw Normal View History

2023-09-17 16:15:03 +01:00
from mkdocs.utils.cache import download_and_cache_url
from datetime import timedelta
import os
import json
import jinja2
import re
2023-09-17 16:15:03 +01:00
UNSPLASH_CACHE_TIME = timedelta(days=14)
MD_ESCAPE_CHARS = r"\_*[]()~`>#+-=|{}.!"
MD_ESCAPE_RE = re.compile(f"([{re.escape(MD_ESCAPE_CHARS)}])")
2023-09-17 16:15:03 +01:00
def get_unsplash_image(image_id):
client_id = os.environ["UNSPLASH_CLIENT_ID"]
url = f"https://api.unsplash.com/photos/{image_id}?client_id={client_id}"
return json.loads(download_and_cache_url(url, UNSPLASH_CACHE_TIME))
def escape_markdown(value):
return MD_ESCAPE_RE.sub(r"\\\1", value)
2023-09-17 16:15:03 +01:00
def on_env(env: jinja2.Environment, config, files):
env.globals["unsplash"] = get_unsplash_image
env.filters["escape_markdown"] = escape_markdown
2023-09-17 16:15:03 +01:00
return env