From 6cafbc79983e7935d360335c42df4e00df163dec Mon Sep 17 00:00:00 2001 From: Alina Marquardt Date: Mon, 10 Apr 2023 07:01:23 +0200 Subject: [PATCH] added basic mustache templating --- src/main.rs | 29 ++++++++++++++++++++++++----- src/templates/index.mustache | 1 + 2 files changed, 25 insertions(+), 5 deletions(-) create mode 100644 src/templates/index.mustache diff --git a/src/main.rs b/src/main.rs index af95fe6..57e4b8e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,27 +1,46 @@ +// for file I/O use std::fs::File; use std::io::{Write, BufReader, BufRead, Error}; +// for timestamping and profiling use chrono; use std::time::Instant; +// for mustache +use mustache; +use std::str; +use std::collections::HashMap; const PUBLISH_PATH: &str = "./pub/"; const TEMPLATE_PATH: &str = "./src/templates/"; fn render_html(file: &str, template_file: &str) { + let now = Instant::now(); // start profiling let output_path = &format!("{}{}", PUBLISH_PATH, file); let template_path = &format!("{}{}", TEMPLATE_PATH, template_file); - let now = Instant::now(); - // TODO: Generate HTML with template and data - let html_string = "

Hello!

"; + // templating + let template = mustache::compile_path(template_path).expect("Failed to compile"); + + let mut data = HashMap::new(); + data.insert("h1", "Hello World"); + + let mut bytes = vec![]; + + template + .render(&mut bytes, &data) + .expect("Failed to render"); + + let html_string = str::from_utf8(&bytes).unwrap(); let output = format!( - "{}\n\n", + "{}\n", html_string, template_path, chrono::offset::Local::now(), now.elapsed(), ); + // write output to file + let result = write_file(output_path, output); match result { Ok(file) => file, @@ -47,6 +66,6 @@ fn write_file(file_path: &str, contents: String) -> Result<(), Error> { fn main() { - render_html("index.html", "index.tmpl"); + render_html("index.html", "index.mustache"); } diff --git a/src/templates/index.mustache b/src/templates/index.mustache new file mode 100644 index 0000000..6f0fe73 --- /dev/null +++ b/src/templates/index.mustache @@ -0,0 +1 @@ +

Page Title: {{ h1 }}