aboutsummaryrefslogtreecommitdiff
path: root/src/post.rs
diff options
context:
space:
mode:
authorRuben Beltran del Rio <git@r.bdr.sh>2024-03-08 14:53:01 +0100
committerRuben Beltran del Rio <git@r.bdr.sh>2024-03-08 14:53:01 +0100
commitf6a545b00a4046879b7cc25c06c37bb6b6880b43 (patch)
treebc7da8066c080ff850d1e423c0e33bd5fb83e095 /src/post.rs
parent2998247083406f914b3647cedd19abf5507bf2c6 (diff)
Use serde and time
Diffstat (limited to 'src/post.rs')
-rw-r--r--src/post.rs87
1 files changed, 87 insertions, 0 deletions
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<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;")
+ }
+}