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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use std::sync::{RwLock, RwLockWriteGuard};
use iron::headers::ContentType;
use iron::modifier::Modifier;
use iron::prelude::*;
use iron::status;
use iron::{typemap, AfterMiddleware};
use plugin::Plugin as PluginFor;
use handlebars::{to_json, Handlebars, TemplateRenderError};
use serde::ser::Serialize as ToJson;
use serde_json::value::Value as Json;
use source::{Source, SourceError};
#[derive(Clone)]
pub struct Template {
name: Option<String>,
content: Option<String>,
value: Json,
}
impl Template {
pub fn new<T: ToJson>(name: &str, value: T) -> Template {
Template {
name: Some(name.to_string()),
value: to_json(&value),
content: None,
}
}
pub fn with<T: ToJson>(content: &str, value: T) -> Template {
Template {
name: None,
value: to_json(&value),
content: Some(content.to_string()),
}
}
}
pub struct HandlebarsEngine {
pub sources: Vec<Box<dyn Source + Send + Sync>>,
pub registry: RwLock<Box<Handlebars<'static>>>,
}
impl typemap::Key for HandlebarsEngine {
type Value = Template;
}
impl Modifier<Response> for Template {
fn modify(self, resp: &mut Response) {
resp.extensions.insert::<HandlebarsEngine>(self);
}
}
impl PluginFor<Response> for HandlebarsEngine {
type Error = ();
fn eval(resp: &mut Response) -> Result<Template, ()> {
match resp.extensions.get::<HandlebarsEngine>() {
Some(t) => Ok(t.clone()),
None => Err(()),
}
}
}
impl HandlebarsEngine {
pub fn new() -> HandlebarsEngine {
HandlebarsEngine {
sources: Vec::new(),
registry: RwLock::new(Box::new(Handlebars::new())),
}
}
pub fn from(reg: Handlebars<'static>) -> HandlebarsEngine {
HandlebarsEngine {
sources: Vec::new(),
registry: RwLock::new(Box::new(reg)),
}
}
pub fn add(&mut self, source: Box<dyn Source + Send + Sync>) {
self.sources.push(source);
}
pub fn reload(&self) -> Result<(), SourceError> {
let mut hbs = self.handlebars_mut();
hbs.clear_templates();
for s in self.sources.iter() {
s.load(&mut hbs)?
}
Ok(())
}
pub fn handlebars_mut(&self) -> RwLockWriteGuard<Box<Handlebars<'static>>> {
self.registry.write().unwrap()
}
}
impl AfterMiddleware for HandlebarsEngine {
fn after(&self, _: &mut Request, mut resp: Response) -> IronResult<Response> {
let page_wrapper = resp.extensions.remove::<HandlebarsEngine>().and_then(|h| {
let hbs = self.registry.read().unwrap();
if let Some(ref name) = h.name {
Some(
hbs.render(name, &h.value)
.map_err(TemplateRenderError::from),
)
} else if let Some(ref content) = h.content {
Some(hbs.render_template(content, &h.value))
} else {
None
}
});
match page_wrapper {
Some(page_result) => match page_result {
Ok(page) => {
if !resp.headers.has::<ContentType>() {
resp.headers.set(ContentType::html());
}
resp.set_mut(page);
Ok(resp)
}
Err(e) => {
info!("{}", e);
Err(IronError::new(e, status::InternalServerError))
}
},
None => Ok(resp),
}
}
fn catch(&self, req: &mut Request, mut err: IronError) -> IronResult<Response> {
err.response = self.after(req, err.response)?;
Err(err)
}
}
#[cfg(test)]
mod test {
use handlebars::{Context, Handlebars, Helper, Output, RenderContext, RenderError};
use iron::prelude::*;
use middleware::*;
use std::collections::BTreeMap;
fn hello_world() -> IronResult<Response> {
let resp = Response::new();
let mut data = BTreeMap::new();
data.insert("title".to_owned(), "Handlebars on Iron".to_owned());
Ok(resp.set(Template::new("index", data)))
}
fn hello_world2() -> IronResult<Response> {
let resp = Response::new();
let mut data = BTreeMap::new();
data.insert("title".to_owned(), "Handlebars on Iron".to_owned());
Ok(resp.set(Template::with("{{title}}", data)))
}
#[test]
fn test_resp_set() {
let mut resp = hello_world().ok().expect("response expected");
match resp.get::<HandlebarsEngine>() {
Ok(h) => {
assert_eq!(h.name.unwrap(), "index".to_string());
assert_eq!(
h.value
.as_object()
.unwrap()
.get(&"title".to_string())
.unwrap()
.as_str()
.unwrap(),
"Handlebars on Iron"
);
}
_ => panic!("template expected"),
}
}
#[test]
fn test_resp_set2() {
let mut resp = hello_world2().ok().expect("response expected");
match resp.get::<HandlebarsEngine>() {
Ok(h) => {
assert_eq!(h.content.unwrap(), "{{title}}".to_string());
assert_eq!(
h.value
.as_object()
.unwrap()
.get(&"title".to_string())
.unwrap()
.as_str()
.unwrap(),
"Handlebars on Iron"
);
}
_ => panic!("template expected"),
}
}
#[test]
fn test_register_helper() {
let hbs = HandlebarsEngine::new();
let mut reg = hbs.handlebars_mut();
reg.register_helper(
"ignore",
Box::new(
|_: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
_: &mut dyn Output|
-> Result<(), RenderError> { Ok(()) },
),
);
}
}