Update cookies example to use contrib Template.

This commit is contained in:
Sergio Benitez 2016-10-08 21:02:42 -07:00
parent a7b180c911
commit 7c6dce266b
3 changed files with 17 additions and 15 deletions

View File

@ -8,4 +8,8 @@ workspace = "../../"
rocket = { path = "../../lib" } rocket = { path = "../../lib" }
rocket_codegen = { path = "../../codegen" } rocket_codegen = { path = "../../codegen" }
lazy_static = "*" lazy_static = "*"
tera = { git = "https://github.com/Keats/tera" }
[dependencies.rocket_contrib]
path = "../../contrib"
default-features = false
features = ["tera_templates"]

View File

@ -3,20 +3,14 @@
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
extern crate rocket_contrib;
extern crate rocket; extern crate rocket;
extern crate tera;
use std::collections::HashMap;
use rocket::response::Redirect; use rocket::response::Redirect;
use rocket::http::{Cookie, Cookies}; use rocket::http::{Cookie, Cookies};
use rocket_contrib::Template;
lazy_static!(static ref TERA: tera::Tera = tera::Tera::new("templates/**/*"););
fn ctxt(message: Option<String>) -> tera::Context {
let mut context = tera::Context::new();
context.add("have_message", &message.is_some());
context.add("message", &message.unwrap_or("".to_string()));
context
}
#[derive(FromForm)] #[derive(FromForm)]
struct Message { struct Message {
@ -30,9 +24,13 @@ fn submit(cookies: &Cookies, message: Message) -> Redirect {
} }
#[get("/")] #[get("/")]
fn index(cookies: &Cookies) -> tera::TeraResult<String> { fn index(cookies: &Cookies) -> Template {
let message = cookies.find("message").map(|msg| msg.value); let mut context = HashMap::new();
TERA.render("index.html", ctxt(message)) if let Some(msg) = cookies.find("message").map(|msg| msg.value) {
context.insert("message", msg);
}
Template::render("index", &context)
} }
fn main() { fn main() {

View File

@ -7,7 +7,7 @@
</head> </head>
<body> <body>
<h1>Rocket Cookie Examples</h1> <h1>Rocket Cookie Examples</h1>
{% if have_message %} {% if message is defined %}
<p>{{ message }}</p> <p>{{ message }}</p>
{% else %} {% else %}
<p>No message yet.</p> <p>No message yet.</p>