tinyweb/templates.py
Derick Phan b17988fc95
Fix custom template rendering and ensure customize page uses default layout
Add use_default parameter to wrap_page/respond so the customize page
always renders with the default template (preventing a broken custom
template from locking out the editor). Also fix the stored custom
template: add <!DOCTYPE html> to prevent quirks mode and remove
newlines inside CSS cursor data URIs that caused CSS parse errors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:45:42 -07:00

40 lines
1.2 KiB
Python

import html
from db import get_setting
def esc(s):
return html.escape(str(s))
def snippet(text, query, ctx=80):
pos = text.lower().find(query.lower())
if pos == -1:
return text[:200]
start = max(0, pos - ctx)
end = min(len(text), pos + len(query) + ctx)
return ("..." if start > 0 else "") + text[start:end] + ("..." if end < len(text) else "")
DEFAULT_TEMPLATE = "<html>\n<head>\n</head>\n<body>\n{{content}}\n</body>\n</html>"
def _default_template():
name = esc(get_setting("site_name", "tinyweb"))
return (
"<html>\n<head>\n</head>\n<body>\n"
f'<p><b><a href="/">{name}</a></b>'
' | <a href="/">search</a> | <a href="/pages">browse</a>'
' | <a href="/tags">tags</a> | <a href="/subscriptions">subscriptions</a>'
' | <a href="/style">customize</a> | <a href="/about">about</a></p>\n'
"<hr>\n{{content}}\n</body>\n</html>"
)
def wrap_page(body_html, use_default=False):
if use_default:
template = _default_template()
else:
template = get_setting("custom_template") or _default_template()
if "{{content}}" not in template:
template = _default_template()
return template.replace("{{content}}", body_html)