38 lines
991 B
Rust
38 lines
991 B
Rust
use handlebars::Handlebars;
|
|
use std::path::Path;
|
|
|
|
const TEMPLATES_DIR: &'static str = "templates";
|
|
static TEMPLATE_FILES: &'static [(&str, &str)] =
|
|
&[("index.html", include_str!("../templates/index.html"))];
|
|
|
|
pub struct Templates<'reg> {
|
|
pub hb: Handlebars<'reg>,
|
|
}
|
|
|
|
pub fn load_templates<'reg>(dir: &Path) -> Templates<'reg> {
|
|
let dir = dir.join(TEMPLATES_DIR);
|
|
std::fs::create_dir_all(&dir).expect("Cannot create templates dir");
|
|
|
|
for &(file, default) in TEMPLATE_FILES {
|
|
let file_path = dir.join(file);
|
|
if !file_path.is_file() {
|
|
std::fs::write(file_path, default)
|
|
.expect(&format!("Cannot write template file {}", file));
|
|
}
|
|
}
|
|
|
|
let mut hb = Handlebars::new();
|
|
for &(file, _) in TEMPLATE_FILES {
|
|
hb.register_template_string(
|
|
file,
|
|
std::str::from_utf8(
|
|
&std::fs::read(dir.join(file))
|
|
.expect(&format!("Cannot read template file`{}`", file)),
|
|
)
|
|
.expect(&format!("Bad encoding in template file `{}`", file)),
|
|
)
|
|
.unwrap();
|
|
}
|
|
Templates { hb }
|
|
}
|