templates.rs
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use crate::errors::{ Result };
use crate::state::{ ApplicationState };
use serde::{ Serialize };
#[derive(Serialize)]
struct SiteContext {
link: String,
name: String,
menu: Vec<LinkContext>,
version: String,
}
#[derive(Serialize)]
struct ListContext {
items: Vec<LinkContext>,
name: String,
}
#[derive(Serialize)]
struct LinkContext {
link: String,
name: String,
}
#[derive(Serialize)]
struct PageContext {
content: String,
name: String,
}
pub(crate) fn index_context(state: &ApplicationState) -> Result<tera::Context> {
let mut context = tera::Context::new();
add_site_context(&mut context, state)?;
add_page_context(&mut context, state, "_index")?;
Ok(context)
}
pub(crate) fn list_context(state: &ApplicationState, list_path: &str) -> Result<tera::Context> {
let mut context = tera::Context::new();
add_site_context(&mut context, state)?;
add_list_context(&mut context, state, list_path)?;
Ok(context)
}
pub(crate) fn page_context(state: &ApplicationState, page_path: &str) -> Result<tera::Context> {
let mut context = tera::Context::new();
add_site_context(&mut context, state)?;
add_page_context(&mut context, state, page_path)?;
Ok(context)
}
fn add_site_context(context: &mut tera::Context, state: &ApplicationState) -> Result<()> {
let menu = state.content.site_menu()
.iter()
.map(|link| LinkContext {
link: link.link.clone(),
name: link.name.clone(),
})
.collect();
let site_context = SiteContext {
link: state.content.site_link(),
name: state.content.site_name(),
menu,
version: env!("CARGO_PKG_VERSION").to_string(),
};
context.insert("site", &site_context);
Ok(())
}
fn add_list_context(context: &mut tera::Context, state: &ApplicationState, list_path: &str) -> Result<()> {
let list = state.content.find_list(list_path)?;
let items = state.content.find_list_items(&list)
.iter()
.map(|item| LinkContext {
link: format!("/page/{}", item.slug),
name: item.name.clone(),
}).collect();
let name = list.name;
let list_context = ListContext {
items,
name,
};
context.insert("list", &list_context);
Ok(())
}
fn add_page_context(context: &mut tera::Context, state: &ApplicationState, page_path: &str) -> Result<()> {
let page = state.content.find_page(page_path)?;
let content = state.content.render_page(&page)?;
let name = page.name;
let page_context = PageContext {
content,
name,
};
context.insert("page", &page_context);
Ok(())
}