44 lines
1.1 KiB
Rust
44 lines
1.1 KiB
Rust
use handlebars::Handlebars;
|
|
use std::path::Path;
|
|
|
|
const TEMPLATES_DIR: &str = "templates";
|
|
static TEMPLATE_FILES: &[(&str, &str)] = &[
|
|
("index.html", include_str!("../templates/index.html")),
|
|
("admin.html", include_str!("../templates/admin.html")),
|
|
(
|
|
"admin_login.html",
|
|
include_str!("../templates/admin_login.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)
|
|
.unwrap_or_else(|_| panic!("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))
|
|
.unwrap_or_else(|_| panic!("Cannot read template file`{}`", file)),
|
|
)
|
|
.unwrap_or_else(|_| panic!("Bad encoding in template file `{}`", file)),
|
|
)
|
|
.unwrap();
|
|
}
|
|
Templates { hb }
|
|
}
|