use crate::metadata::Metadata; use crate::template::{Context, Value}; use std::collections::HashMap; pub struct Post { pub metadata: Metadata, pub index: u8, pub html: String, pub raw: String, } impl Post { pub fn to_template_context(posts: &[Post]) -> Context { let mut context = HashMap::new(); let posts_collection = posts.iter().map(Post::to_template_value).collect(); context.insert("has_posts".to_string(), Value::Bool(!posts.is_empty())); context.insert( "posts_length".to_string(), Value::Unsigned(posts.len().try_into().unwrap()), ); context.insert("posts".to_string(), Value::Collection(posts_collection)); context } pub fn to_template_value(&self) -> Context { let mut context = HashMap::new(); context.insert( "id".to_string(), Value::String(self.metadata.id.to_string()), ); context.insert( "created_on".to_string(), Value::Unsigned(self.metadata.created_on), ); if let Some(created_on_utc) = self.metadata.created_on_utc() { context.insert("created_on_utc".to_string(), Value::String(created_on_utc)); } context.insert("title".to_string(), Value::String(self.title())); context.insert("index".to_string(), Value::Unsigned(self.index.into())); context.insert("html".to_string(), Value::String(self.html.to_string())); context.insert( "escaped_html".to_string(), Value::String(self.escaped_html().to_string()), ); context.insert("raw".to_string(), Value::String(self.raw.to_string())); context } fn title(&self) -> String { self.raw .lines() .next() .unwrap() .replace('#', "") .replace('&', "&") .trim() .to_string() } fn escaped_html(&self) -> String { self.html .replace('&', "&") .replace('<', "<") .replace('>', ">") .replace('"', """) .replace('\'', "'") } }