Browse Source

Don't read templates in a loop

master
Dylan Baker 5 years ago
parent
commit
20d0966f47
1 changed files with 11 additions and 10 deletions
  1. 11
    10
      src/main.rs

+ 11
- 10
src/main.rs View File

@@ -42,9 +42,7 @@ fn read_posts_dir(cwd: &path::PathBuf) -> fs::ReadDir {
42 42
     }
43 43
 }
44 44
 
45
-fn render_post(cwd: &path::PathBuf, layout: &str, post: &Post) {
46
-    let post_template = fs::read_to_string(cwd.join("templates").join("post.html"))
47
-        .expect("Couldn't find post template");
45
+fn render_post(cwd: &path::PathBuf, layout: &str, post_template: &str, post: &Post) {
48 46
     let output = layout.replace(
49 47
         "{{ contents }}",
50 48
         &post_template
@@ -64,10 +62,7 @@ fn render_post(cwd: &path::PathBuf, layout: &str, post: &Post) {
64 62
     ).expect("Unable to write file");
65 63
 }
66 64
 
67
-fn render_post_listing(cwd: &path::PathBuf, layout: &str, posts: &Vec<Post>) {
68
-    let post_item_template =
69
-        fs::read_to_string(cwd.join("templates").join("post_listing_item.html"))
70
-            .expect("Couldn't find post listing item template");
65
+fn render_post_listing(cwd: &path::PathBuf, layout: &str, post_item_template: &str, posts: &Vec<Post>) {
71 66
     let post_listing = posts
72 67
         .iter()
73 68
         .map(|ref post| {
@@ -92,20 +87,26 @@ fn main() {
92 87
         },
93 88
     }
94 89
 
95
-    let layout = fs::read_to_string(&cwd.join("templates").join("layout.html"))
90
+    let layout_template = fs::read_to_string(&cwd.join("templates").join("layout.html"))
96 91
         .expect("Couldn't find layout template");
92
+    let post_template = fs::read_to_string(cwd.join("templates").join("post.html"))
93
+        .expect("Couldn't find post template");
94
+    let post_item_template =
95
+        fs::read_to_string(cwd.join("templates").join("post_listing_item.html"))
96
+            .expect("Couldn't find post listing item template");
97
+
97 98
     let post_paths = read_posts_dir(&cwd.join("posts"));
98 99
     let mut posts: Vec<Post> = vec![];
99 100
     for path in post_paths {
100 101
         match path {
101 102
             Ok(p) => {
102 103
                 let post = parse_post(p.path());
103
-                render_post(&cwd, &layout, &post);
104
+                render_post(&cwd, &layout_template, &post_template, &post);
104 105
                 posts.push(post);
105 106
             }
106 107
             Err(err) => panic!(err),
107 108
         }
108 109
     }
109 110
 
110
-    render_post_listing(&cwd, &layout, &posts);
111
+    render_post_listing(&cwd, &layout_template, &post_item_template, &posts);
111 112
 }

Loading…
Cancel
Save