Browse Source

Use helper render function

master
Dylan Baker 3 years ago
parent
commit
c94bbe605c
1 changed files with 9 additions and 9 deletions
  1. 9
    9
      src/main.rs

+ 9
- 9
src/main.rs View File

@@ -81,6 +81,12 @@ async fn read_all_posts() -> Result<Vec<Post>, Error> {
81 81
     Ok(posts)
82 82
 }
83 83
 
84
+fn render(template: &str, context: &Context) -> Result<Body, tide::Error> {
85
+    let tera = Tera::new("templates/**/*.html")?;
86
+    let html = tera.render(template, &context)?;
87
+    Ok(Body::from_string(html))
88
+}
89
+
84 90
 #[async_std::main]
85 91
 async fn main() -> std::io::Result<()> {
86 92
     dotenv::dotenv().ok();
@@ -89,11 +95,9 @@ async fn main() -> std::io::Result<()> {
89 95
 
90 96
     app.with(After(|mut res: Response| async {
91 97
         if let Some(err) = res.downcast_error::<async_std::io::Error>() {
92
-            let tera = Tera::new("templates/**/*.html")?;
93 98
             let mut context = Context::new();
94 99
             context.insert("error", &err.to_string());
95
-            let html = tera.render("error.html", &context)?;
96
-            res.set_body(html);
100
+            res.set_body(render("error.html", &context)?);
97 101
             res.set_status(StatusCode::InternalServerError);
98 102
         }
99 103
 
@@ -116,14 +120,12 @@ async fn main() -> std::io::Result<()> {
116 120
     ));
117 121
 
118 122
     app.at("/").get(|req: tide::Request<()>| async move {
119
-        let tera = Tera::new("templates/**/*.html")?;
120 123
         let posts = read_all_posts().await?;
121 124
         let mut context = Context::new();
122 125
         context.insert("posts", &posts);
123 126
         let logged_in: bool = req.session().get("logged_in").unwrap_or(false);
124 127
         context.insert("logged_in", &logged_in);
125
-        let html = tera.render("index.html", &context)?;
126
-        Ok(Body::from_string(html))
128
+        render("index.html", &context)
127 129
     });
128 130
 
129 131
     app.at("/posts")
@@ -143,7 +145,6 @@ async fn main() -> std::io::Result<()> {
143 145
 
144 146
     app.at("/login")
145 147
         .get(|mut req: tide::Request<()>| async move {
146
-            let tera = Tera::new("templates/**/*.html")?;
147 148
             let mut context = Context::new();
148 149
             let logged_in: bool = req.session().get("logged_in").unwrap_or(false);
149 150
             context.insert("logged_in", &logged_in);
@@ -154,8 +155,7 @@ async fn main() -> std::io::Result<()> {
154 155
                 }
155 156
                 None => {}
156 157
             }
157
-            let html = tera.render("login.html", &context)?;
158
-            Ok(Body::from_string(html))
158
+            render("login.html", &context)
159 159
         })
160 160
         .post(|mut req: tide::Request<()>| async move {
161 161
             let logged_in: bool = req.session().get("logged_in").unwrap_or(false);

Loading…
Cancel
Save