1
0
Fork 0
website/src/handlers/posts.rs

45 lines
1.2 KiB
Rust
Raw Normal View History

2022-09-05 00:02:58 +02:00
use std::sync::Arc;
2022-09-05 00:05:24 +02:00
use axum::{extract::Path, response::Html, Extension};
use pulldown_cmark::{html, Options, Parser};
2022-09-05 00:02:58 +02:00
use tracing::log::*;
2022-09-05 00:05:24 +02:00
use super::{Error, Result};
use crate::{handlers::PageContext, State};
2022-09-05 00:02:58 +02:00
2022-09-05 00:05:24 +02:00
pub async fn view(Path(slug): Path<String>, Extension(state): Extension<Arc<State>>) -> Result {
2022-09-05 00:02:58 +02:00
let post = state
.posts
.iter()
.find(|p| p.slug == slug)
.ok_or(Error::NotFound)?;
info!("Requested post: {}", slug);
let options = Options::all();
let parser = Parser::new_ext(&post.content, options);
let mut out = String::new();
html::push_html(&mut out, parser);
let ctx =
tera::Context::from_serialize(PageContext { content: out }).map_err(|_| Error::NotFound)?;
let res = state.tera.render("post.html", &ctx).map_err(|e| {
error!("Failed rendering post: {}", e);
Error::NotFound
})?;
Ok(Html(res.into()))
}
pub async fn index(Extension(state): Extension<Arc<State>>) -> Result {
let mut ctx = tera::Context::new();
ctx.insert("posts", &state.posts);
let res = state.tera.render("postsindex.html", &ctx).map_err(|e| {
error!("Failed rendering posts index: {}", e);
Error::NotFound
})?;
Ok(Html(res.into()))
}