]> git.r.bdr.sh - rbdr/blog/blobdiff - src/post.rs
Use serde and time
[rbdr/blog] / src / post.rs
index 548a5cb7d10d0fec976a2af72084313799c832b6..0250bff933c040d10ad98fc0d947163682a916c1 100644 (file)
@@ -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<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("&", "&amp;")
+            .trim()
+            .to_string()
+    }
+
+    fn escaped_html(&self) -> String {
+        self.html.replace("&", "&amp;")
+            .replace("<", "&lt;")
+            .replace(">", "&gt;")
+            .replace("\"", "&quot;")
+            .replace("'", "&apos;")
+    }
+}