aboutsummaryrefslogtreecommitdiff
path: root/src/post.rs
blob: afe6b7726fa36936432a7caa4ddc1f640e9d1311 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use crate::metadata::Metadata;
use crate::template::{TemplateContext, TemplateValue};
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: &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;")
    }
}