]> git.r.bdr.sh - rbdr/blog/blob - src/post.rs
Set rust
[rbdr/blog] / src / post.rs
1 use std::collections::HashMap;
2 use crate::metadata::Metadata;
3 use crate::template::{TemplateContext, TemplateValue};
4
5 pub struct Post {
6 pub metadata: Metadata,
7 pub index: u8,
8 pub html: String,
9 pub raw: String
10 }
11
12 impl Post {
13 pub fn to_template_context(posts: &Vec<Post>) -> TemplateContext {
14 let mut context = HashMap::new();
15
16 let posts_collection = posts
17 .iter()
18 .map(|post| post.to_template_value())
19 .collect();
20 context.insert(
21 "has_posts".to_string(),
22 TemplateValue::Bool(posts.len() > 0)
23 );
24 context.insert(
25 "posts_length".to_string(),
26 TemplateValue::Unsigned(
27 posts.len().try_into().unwrap()
28 )
29 );
30 context.insert(
31 "posts".to_string(),
32 TemplateValue::Collection(posts_collection)
33 );
34
35 context
36 }
37 pub fn to_template_value(&self) -> TemplateContext {
38 let mut context = HashMap::new();
39
40 context.insert(
41 "id".to_string(),
42 TemplateValue::String(format!("{}", self.metadata.id))
43 );
44 context.insert(
45 "created_on".to_string(),
46 TemplateValue::Unsigned(self.metadata.created_on)
47 );
48
49 if let Some(created_on_utc) = self.metadata.created_on_utc() {
50 context.insert(
51 "created_on_utc".to_string(),
52 TemplateValue::String(created_on_utc)
53 );
54 }
55
56 context.insert(
57 "title".to_string(),
58 TemplateValue::String(self.title())
59 );
60 context.insert(
61 "index".to_string(),
62 TemplateValue::Unsigned(self.index.into())
63 );
64 context.insert(
65 "html".to_string(),
66 TemplateValue::String(format!("{}", self.html))
67 );
68 context.insert(
69 "escaped_html".to_string(),
70 TemplateValue::String(format!("{}", self.escaped_html()))
71 );
72 context.insert(
73 "raw".to_string(),
74 TemplateValue::String(format!("{}", self.raw))
75 );
76 context
77 }
78
79 fn title(&self) -> String {
80 self.raw.trim()
81 .split('\n').next().unwrap()
82 .replace('#', "")
83 .replace("&", "&amp;")
84 .trim()
85 .to_string()
86 }
87
88 fn escaped_html(&self) -> String {
89 self.html.replace("&", "&amp;")
90 .replace("<", "&lt;")
91 .replace(">", "&gt;")
92 .replace("\"", "&quot;")
93 .replace("'", "&apos;")
94 }
95 }