lib/
templator.rs

1use crate::config::Config;
2use serde_derive::Serialize;
3use tera::{Context, Tera};
4
5fn template_one(text: &str, context: &Context, auto_escape: bool) -> tera::Result<String> {
6    Tera::one_off(text, context, auto_escape)
7}
8
9#[derive(Serialize, Debug, Clone)]
10pub struct Post {
11    config: Config,
12    body: String,
13    header: serde_yaml::Value,
14    file_name: String,
15}
16
17#[derive(Serialize, Debug)]
18pub struct Index<'a> {
19    config: &'a Config,
20    posts: &'a [Post],
21}
22
23#[derive(Serialize, Debug)]
24pub struct Feed<'a> {
25    config: &'a Config,
26    posts: &'a [Post],
27}
28
29impl Post {
30    pub fn new(config: Config, body: String, header: serde_yaml::Value, file_name: String) -> Post {
31        Post {
32            config,
33            body,
34            header,
35            file_name,
36        }
37    }
38
39    pub fn template_text(&self, file_content: &str) -> tera::Result<String> {
40        let mut context = Context::new();
41
42        context.insert("config", &self.config);
43        context.insert("post", &(&self.body, &self.header));
44
45        template_one(file_content, &context, false)
46    }
47}
48
49impl Index<'_> {
50    pub fn new<'a>(config: &'a Config, posts: &'a [Post]) -> Index<'a> {
51        Index { config, posts }
52    }
53
54    pub fn template_text(&self, file_content: &str) -> tera::Result<String> {
55        let mut context = Context::new();
56
57        context.insert("config", &self.config);
58        context.insert("posts", &self.posts);
59
60        template_one(file_content, &context, false)
61    }
62}
63
64impl Feed<'_> {
65    pub fn new<'a>(config: &'a Config, posts: &'a [Post]) -> Feed<'a> {
66        Feed { config, posts }
67    }
68
69    pub fn template_text(&self, file_content: &str) -> tera::Result<String> {
70        let mut context = Context::new();
71
72        context.insert("config", &self.config);
73        context.insert("posts", &self.posts);
74
75        template_one(file_content, &context, true)
76    }
77}