1
0
Fork 0
website/src/handlers/posts.rs
2022-09-05 00:02:58 +02:00

47 lines
1.2 KiB
Rust

use std::sync::Arc;
use axum::{extract::Path, Extension, response::Html};
use pulldown_cmark::{Options, Parser, html};
use tracing::log::*;
use crate::{State, handlers::PageContext};
use super::{Result, Error};
pub async fn view(
Path(slug): Path<String>,
Extension(state): Extension<Arc<State>>,
) -> Result {
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()))
}