+use std::collections::HashMap;
use crate::metadata::Metadata;
+use crate::template::{TemplateContext, TemplateValue};
pub struct Post {
pub metadata: Metadata,
pub html: String,
pub raw: String
}
+
+impl Post {
+ pub fn to_template_context(posts: &Vec<Post>) -> 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("'", "'")
+ }
+}