X-Git-Url: https://git.r.bdr.sh/rbdr/blog/blobdiff_plain/2998247083406f914b3647cedd19abf5507bf2c6..f6a545b00a4046879b7cc25c06c37bb6b6880b43:/src/post.rs diff --git a/src/post.rs b/src/post.rs index 548a5cb..0250bff 100644 --- a/src/post.rs +++ b/src/post.rs @@ -1,4 +1,6 @@ +use std::collections::HashMap; use crate::metadata::Metadata; +use crate::template::{TemplateContext, TemplateValue}; pub struct Post { pub metadata: Metadata, @@ -6,3 +8,88 @@ pub struct Post { pub html: String, pub raw: String } + +impl Post { + pub fn to_template_context(posts: &Vec) -> TemplateContext { + let mut context = HashMap::new(); + + let posts_collection = posts + .iter() + .map(|post| post.to_template_value()) + .collect(); + context.insert( + "has_posts".to_string(), + TemplateValue::Bool(posts.len() > 0) + ); + context.insert( + "posts_length".to_string(), + TemplateValue::Unsigned( + posts.len().try_into().unwrap() + ) + ); + context.insert( + "posts".to_string(), + TemplateValue::Collection(posts_collection) + ); + + context + } + pub fn to_template_value(&self) -> TemplateContext { + let mut context = HashMap::new(); + + context.insert( + "id".to_string(), + TemplateValue::String(format!("{}", self.metadata.id)) + ); + context.insert( + "created_on".to_string(), + TemplateValue::Unsigned(self.metadata.created_on) + ); + + if let Some(created_on_utc) = self.metadata.created_on_utc() { + context.insert( + "created_on_utc".to_string(), + TemplateValue::String(created_on_utc) + ); + } + + context.insert( + "title".to_string(), + TemplateValue::String(self.title()) + ); + context.insert( + "index".to_string(), + TemplateValue::Unsigned(self.index.into()) + ); + context.insert( + "html".to_string(), + TemplateValue::String(format!("{}", self.html)) + ); + context.insert( + "escaped_html".to_string(), + TemplateValue::String(format!("{}", self.escaped_html())) + ); + context.insert( + "raw".to_string(), + TemplateValue::String(format!("{}", self.raw)) + ); + context + } + + fn title(&self) -> String { + self.raw.trim() + .split('\n').next().unwrap() + .replace('#', "") + .replace("&", "&") + .trim() + .to_string() + } + + fn escaped_html(&self) -> String { + self.html.replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace("\"", """) + .replace("'", "'") + } +}