From c44c2243debb1173cce727dc5fa6dd8fa1e8dd2a Mon Sep 17 00:00:00 2001 From: Michal Vanko Date: Tue, 16 Jan 2024 21:56:29 +0100 Subject: [PATCH] filter listing by tag --- axum_server/src/pages/post_list.rs | 26 ++++++++++++++++++++++---- axum_server/src/router.rs | 1 + 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/axum_server/src/pages/post_list.rs b/axum_server/src/pages/post_list.rs index aac0e67..3f95cad 100644 --- a/axum_server/src/pages/post_list.rs +++ b/axum_server/src/pages/post_list.rs @@ -1,5 +1,5 @@ use askama::Template; -use axum::http::StatusCode; +use axum::{extract::Path, http::StatusCode}; use tokio::fs::read_dir; use tracing::info; @@ -11,10 +11,13 @@ use super::post::PostMetadata; #[template(path = "post_list.html")] pub struct PostListTemplate { pub posts: Vec>, - // TODO tags and pagination + pub tag: Option, } -pub async fn render_post_list() -> Result { +pub async fn render_post_list(tag: Option>) -> Result { + // I will forget what happens here in a week. But essentially it's pattern matching and shadowing + let tag = tag.map(|Path(tag)| tag); + let path = "../_posts/blog/"; let mut dir = read_dir(path) .await @@ -33,7 +36,22 @@ pub async fn render_post_list() -> Result { posts.push(post); } - Ok(PostListTemplate { posts }) + let posts = match &tag { + Some(tag) => posts + .into_iter() + .filter(|post| { + post.metadata + .tags + .iter() + .map(|post_tag| post_tag.to_lowercase()) + .collect::() + .contains(&tag.to_lowercase()) + }) + .collect(), + None => posts, + }; + + Ok(PostListTemplate { posts, tag }) } // TODO Do we want pagination or not? Ask designer diff --git a/axum_server/src/router.rs b/axum_server/src/router.rs index 1bc8bf9..cf87917 100644 --- a/axum_server/src/router.rs +++ b/axum_server/src/router.rs @@ -7,6 +7,7 @@ pub fn get_router() -> Router { Router::new() .route("/", get(render_index)) .route("/blog", get(render_post_list)) + .route("/blog/tags/:tag", get(render_post_list)) .route("/blog/:post_id", get(render_post)) .layer( TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {