media-collection-crud/src/handlers.rs

78 lines
2.1 KiB
Rust

use handlebars::{Handlebars, no_escape};
use handlebars_iron::{DirectorySource, HandlebarsEngine};
use handlebars_iron::handlebars::to_json;
use handlebars_iron::Template;
use iron::prelude::{Request, Response};
use iron::{IronResult, Set, status};
use mount::Mount;
use serde::ser::Serialize as ToJson;
use serde_json::value::Map;
use staticfile::Static;
use std::error::Error;
use std::path::Path;
use std::sync::Arc;
pub fn template_engine() -> Arc<HandlebarsEngine> {
let views_ext = ".hbs";
let views_path = "./src/views";
let mut hbs = Handlebars::new();
// @TODO Find better solution for rendering included template file
hbs.register_escape_fn(no_escape);
let mut hbse = HandlebarsEngine::from(hbs);
hbse.add(Box::new(
DirectorySource::new(views_path, views_ext)
));
if let Err(r) = hbse.reload() {
panic!("{:?}", r.description());
}
let hbse_ref = Arc::new(hbse);
if cfg!(debug_assertions) {
println!("Templates are being watched.");
use handlebars_iron::Watchable;
hbse_ref.watch(views_path);
}
hbse_ref
}
pub fn render_page<T: ToJson>(name: &str, template_data: T) -> Template {
let template_engine = template_engine().clone();
let template_registry = template_engine.handlebars_mut();
let page = template_registry.render(name, &template_data).unwrap();
let mut data = Map::new();
data.insert("page".to_string(), to_json(page));
Template::new("layout/base", data)
}
pub struct AssetsHandler;
impl AssetsHandler {
pub fn new(prefix: &str, mount_path: &str) -> Mount {
let mut assets_mount = Mount::new();
assets_mount.mount(prefix, Static::new(Path::new(mount_path)));
assets_mount
}
}
pub fn hello_world (_request: &mut Request) -> IronResult<Response> {
use serde_json::value::{Map, Value};
let mut data = Map::new();
data.insert("title".to_string(), to_json(&"Media Collection CRUD".to_owned()));
let mut response = Response::new();
response.set_mut(render_page("index", data))
.set_mut(status::Ok);
Ok(response)
}