Debian Codegraph @

third_party/rust/warp/examples/handlebars_template.rs

raw
1 #![deny(warnings)]
2 use std::sync::Arc;
3
4 use handlebars::Handlebars;
5 use serde::Serialize;
6 use serde_json::json;
7 use warp::Filter;
8
9 struct WithTemplate<T: Serialize> {
10 name: &'static str,
11 value: T,
12 }
13
14 fn render<T>(template: WithTemplate<T>, hbs: Arc<Handlebars<'_>>) -> impl warp::Reply
15 where
16 T: Serialize,
17 {
18 let render = hbs
19 .render(template.name, &template.value)
20 .unwrap_or_else(|err| err.to_string());
21 warp::reply::html(render)
22 }
23
24 #[tokio::main]
25 async fn main() {
26 let template = "<!DOCTYPE html>
27 <html>
28 <head>
29 <title>Warp Handlebars template example</title>
30 </head>
31 <body>
32 <h1>Hello {{user}}!</h1>
33 </body>
34 </html>";
35
36 let mut hb = Handlebars::new();
37 // register the template
38 hb.register_template_string("template.html", template)
39 .unwrap();
40
41 // Turn Handlebars instance into a Filter so we can combine it
42 // easily with others...
43 let hb = Arc::new(hb);
44
45 // Create a reusable closure to render template
46 let handlebars = move |with_template| render(with_template, hb.clone());
47
48 //GET /
49 let route = warp::get()
50 .and(warp::path::end())
51 .map(|| WithTemplate {
52 name: "template.html",
53 value: json!({"user" : "Warp"}),
54 })
55 .map(handlebars);
56
57 warp::serve(route).run(([127, 0, 0, 1], 3030)).await;
58 }