1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 16:32:43 +01:00
actix-extras/examples/template_tera/src/main.rs

54 lines
1.8 KiB
Rust
Raw Normal View History

2017-12-18 22:41:52 +01:00
extern crate actix;
extern crate actix_web;
extern crate env_logger;
#[macro_use]
extern crate tera;
use actix::*;
2017-12-18 22:41:52 +01:00
use actix_web::*;
#[cfg(target_os = "linux")] use actix::actors::signal::{ProcessSignals, Subscribe};
2017-12-18 22:41:52 +01:00
struct State {
template: tera::Tera, // <- store tera template in application state
}
2017-12-21 01:32:31 +01:00
fn index(req: HttpRequest<State>) -> Result<HttpResponse> {
2017-12-18 22:41:52 +01:00
let s = if let Some(name) = req.query().get("name") { // <- submitted form
let mut ctx = tera::Context::new();
2017-12-28 04:29:04 +01:00
ctx.add("name", &name.to_owned());
2017-12-18 22:41:52 +01:00
ctx.add("text", &"Welcome!".to_owned());
2017-12-21 01:32:31 +01:00
req.state().template.render("user.html", &ctx)
.map_err(|_| error::ErrorInternalServerError("Template error"))?
2017-12-18 22:41:52 +01:00
} else {
2017-12-21 01:32:31 +01:00
req.state().template.render("index.html", &tera::Context::new())
.map_err(|_| error::ErrorInternalServerError("Template error"))?
2017-12-18 22:41:52 +01:00
};
2017-12-21 01:32:31 +01:00
Ok(httpcodes::HTTPOk.build()
.content_type("text/html")
.body(s)?)
2017-12-18 22:41:52 +01:00
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init();
let sys = actix::System::new("tera-example");
2017-12-30 16:10:29 +01:00
let addr = HttpServer::new(|| {
2017-12-18 22:41:52 +01:00
let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
Application::with_state(State{template: tera})
// enable logger
2017-12-27 04:59:41 +01:00
.middleware(middleware::Logger::default())
2017-12-18 22:41:52 +01:00
.resource("/", |r| r.method(Method::GET).f(index))})
.bind("127.0.0.1:8080").unwrap()
2017-12-19 18:08:36 +01:00
.start();
2017-12-18 22:41:52 +01:00
if cfg!(target_os = "linux") { // Subscribe to unix signals
let signals = Arbiter::system_registry().get::<ProcessSignals>();
signals.send(Subscribe(addr.subscriber()));
}
2017-12-30 16:10:29 +01:00
2017-12-18 22:41:52 +01:00
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}