added basic mustache templating

main
Alina Marquardt 2023-04-10 07:01:23 +02:00
parent 7421e8a5e1
commit 6cafbc7998
2 changed files with 25 additions and 5 deletions

View File

@ -1,27 +1,46 @@
// for file I/O
use std::fs::File; use std::fs::File;
use std::io::{Write, BufReader, BufRead, Error}; use std::io::{Write, BufReader, BufRead, Error};
// for timestamping and profiling
use chrono; use chrono;
use std::time::Instant; use std::time::Instant;
// for mustache
use mustache;
use std::str;
use std::collections::HashMap;
const PUBLISH_PATH: &str = "./pub/"; const PUBLISH_PATH: &str = "./pub/";
const TEMPLATE_PATH: &str = "./src/templates/"; const TEMPLATE_PATH: &str = "./src/templates/";
fn render_html(file: &str, template_file: &str) { fn render_html(file: &str, template_file: &str) {
let now = Instant::now(); // start profiling
let output_path = &format!("{}{}", PUBLISH_PATH, file); let output_path = &format!("{}{}", PUBLISH_PATH, file);
let template_path = &format!("{}{}", TEMPLATE_PATH, template_file); let template_path = &format!("{}{}", TEMPLATE_PATH, template_file);
let now = Instant::now(); // templating
// TODO: Generate HTML with template and data let template = mustache::compile_path(template_path).expect("Failed to compile");
let html_string = "<h1>Hello!</h1>";
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!( let output = format!(
"{}\n\n<!--\n {}\n {}\n generated in {:.2?}\n-->", "{}\n<!--\n {}\n {}\n generated in {:.2?}\n-->",
html_string, html_string,
template_path, template_path,
chrono::offset::Local::now(), chrono::offset::Local::now(),
now.elapsed(), now.elapsed(),
); );
// write output to file
let result = write_file(output_path, output); let result = write_file(output_path, output);
match result { match result {
Ok(file) => file, Ok(file) => file,
@ -47,6 +66,6 @@ fn write_file(file_path: &str, contents: String) -> Result<(), Error> {
fn main() { fn main() {
render_html("index.html", "index.tmpl"); render_html("index.html", "index.mustache");
} }

View File

@ -0,0 +1 @@
<h1>Page Title: {{ h1 }}</h1>