Skip to main content

max / makenotwork

1.2 KB · 27 lines History Blame Raw
1 //! Rendering helpers: Askama fragment rendering and HTML escaping for raw
2 //! `format!`-built markup.
3
4 /// Render an Askama fragment to an HTML string, surfacing a render failure as an
5 /// `AppError` (mapped to 500 + an `HX-Error` header by the error responder) instead
6 /// of the silent `.render().unwrap_or_default()` blank swap, which installs an
7 /// empty HTMX fragment with no error signal (ultra-fuzz Run 12 doubledown S-A). Use
8 /// this for HTMX fragment handlers that return `Result`.
9 pub fn render_fragment(template: &impl askama::Template) -> crate::error::Result<String> {
10 template.render().map_err(|e| {
11 tracing::error!(error = ?e, "fragment render failed");
12 crate::error::AppError::Internal(anyhow::anyhow!("template render failed"))
13 })
14 }
15
16 /// Escape HTML special characters, including `'` so the output is safe in
17 /// single-quoted attribute contexts as well as element text. Use whenever a
18 /// value is interpolated into a raw `format!`-built HTML string instead of an
19 /// auto-escaped template.
20 pub fn escape_html(s: &str) -> String {
21 s.replace('&', "&amp;")
22 .replace('<', "&lt;")
23 .replace('>', "&gt;")
24 .replace('"', "&quot;")
25 .replace('\'', "&#39;")
26 }
27