Add 'TemplateMetadata' request guard to contrib.

The request guard allows a user to query information about loaded
templates. In particular, a user can check whether a template was
loaded.
This commit is contained in:
Marc Mettke 2018-07-09 14:36:40 +02:00 committed by Sergio Benitez
parent 5e2502f028
commit c381386098
5 changed files with 130 additions and 4 deletions

View File

@ -37,5 +37,8 @@ handlebars = { version = "0.32", optional = true }
glob = { version = "^0.2", optional = true }
tera = { version = "0.11", optional = true }
[dev-dependencies]
rocket_codegen = { version = "0.4.0-dev", path = "../../core/codegen" }
[package.metadata.docs.rs]
all-features = true

View File

@ -74,7 +74,7 @@ pub use msgpack::{MsgPack, MsgPackError};
mod templates;
#[cfg(feature = "templates")]
pub use templates::{Template, Engines};
pub use templates::{Engines, Template, TemplateMetadata};
#[cfg(feature = "uuid")]
mod uuid;

View File

@ -0,0 +1,79 @@
use rocket::{http::Status, outcome, request::{FromRequest, Outcome}, Request, State};
use templates::context::Context;
/// The TemplateEngine type: implements `FromRequest`, allowing you to communicate
/// directly with the template engines.
///
/// Using it in a request handler always returns successfully except when the [`Template::fairing()`]
/// wasn't attached to rocket.
///
/// # Usage
///
/// Ensure that the template [fairing](/rocket/fairing/) is attached to
/// your Rocket application:
///
/// ```rust
/// extern crate rocket;
/// extern crate rocket_contrib;
///
/// use rocket_contrib::Template;
///
/// fn main() {
/// rocket::ignite()
/// // ...
/// .attach(Template::fairing())
/// // ...
/// # ;
/// }
/// ```
///
/// The `TemplateEngine` type implements Rocket's `FromRequest` trait, so it can be
/// used as Parameter in a request handler:
///
/// ```rust,ignore
/// #[get("/")]
/// fn homepage(engine: TemplateEngine) -> Template {
/// if engine.template_exists("specific") {
/// return Template::render("specfic", json!({}));
/// }
/// Template::render("fallback", json!({}))
/// }
/// ```
pub struct TemplateMetadata<'a>(&'a Context);
impl<'a> TemplateMetadata<'a> {
/// Returns `true` if the template with name `name` was loaded at start-up time. Otherwise,
/// returns `false`.
///
/// # Example
///
/// ```rust,ignore
/// #[get("/")]
/// fn homepage(engine: TemplateEngine) -> Template {
/// if engine.template_exists("specific") {
/// return Template::render("specfic", json!({}));
/// }
/// Template::render("fallback", json!({}))
/// }
/// ```
pub fn contains_template(&self, name: &str) -> bool {
self.0.templates.contains_key(name)
}
}
impl<'a, 'r> FromRequest<'a, 'r> for TemplateMetadata<'a> {
type Error = ();
fn from_request(request: &'a Request) -> Outcome<Self, ()> {
request
.guard::<State<Context>>()
.succeeded()
.and_then(|ctxt| Some(outcome::Outcome::Success(TemplateMetadata(ctxt.inner()))))
.unwrap_or_else(|| {
error_!("Uninitialized template context: missing fairing.");
info_!("To use templates, you must attach `Template::fairing()`.");
info_!("See the `Template` documentation for more information.");
outcome::Outcome::Failure((Status::InternalServerError, ()))
})
}
}

View File

@ -6,8 +6,10 @@ extern crate glob;
#[cfg(feature = "handlebars_templates")] mod handlebars_templates;
mod engine;
mod context;
mod metadata;
pub use self::engine::Engines;
pub use self::metadata::TemplateMetadata;
use self::engine::Engine;
use self::context::Context;

View File

@ -1,14 +1,21 @@
#![feature(plugin, decl_macro)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
#[cfg(feature = "templates")]
mod templates_tests {
use rocket::{http::RawStr, response::content::Plain, Rocket};
use rocket::config::{Config, Environment};
use rocket_contrib::{Template, TemplateMetadata};
use std::env;
use std::path::PathBuf;
use rocket::Rocket;
use rocket::config::{Config, Environment};
use rocket_contrib::Template;
#[get("/<engine>/<name>")]
fn contains_template(template_metadata: TemplateMetadata, engine: &RawStr, name: &RawStr) -> Plain<String> {
Plain(template_metadata.contains_template(&format!("{}/{}", engine, name)).to_string())
}
fn template_root() -> PathBuf {
let cwd = env::current_dir().expect("current working directory");
@ -21,12 +28,15 @@ mod templates_tests {
.expect("valid configuration");
::rocket::custom(config).attach(Template::fairing())
.mount("/", routes![contains_template])
}
#[cfg(feature = "tera_templates")]
mod tera_tests {
use super::*;
use std::collections::HashMap;
use rocket::http::Status;
use rocket::local::Client;
const UNESCAPED_EXPECTED: &'static str
= "\nh_start\ntitle: _test_\nh_end\n\n\n<script />\n\nfoot\n";
@ -48,12 +58,31 @@ mod templates_tests {
let template = Template::show(&rocket, "tera/html_test", &map);
assert_eq!(template, Some(ESCAPED_EXPECTED.into()));
}
#[test]
fn test_template_engine_with_tera() {
let client = Client::new(rocket()).unwrap();
let mut response = client.get("/tera/txt_test").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().unwrap().into_string().unwrap(), "true");
let mut response = client.get("/tera/html_test").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().unwrap().into_string().unwrap(), "true");
let mut response = client.get("/tera/not_existing").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().unwrap().into_string().unwrap(), "false");
}
}
#[cfg(feature = "handlebars_templates")]
mod handlebars_tests {
use super::*;
use std::collections::HashMap;
use rocket::http::Status;
use rocket::local::Client;
const EXPECTED: &'static str
= "Hello _test_!\n\n<main> &lt;script /&gt; hi </main>\nDone.\n\n";
@ -69,5 +98,18 @@ mod templates_tests {
let template = Template::show(&rocket, "hbs/test", &map);
assert_eq!(template, Some(EXPECTED.into()));
}
#[test]
fn test_template_engine_with_handlebars() {
let client = Client::new(rocket()).unwrap();
let mut response = client.get("/hbs/test").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().unwrap().into_string().unwrap(), "true");
let mut response = client.get("/hbs/not_existing").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().unwrap().into_string().unwrap(), "false");
}
}
}