Clean up 'TemplateMetadata' implementation.

This commit is contained in:
Sergio Benitez 2018-07-10 17:07:53 -07:00
parent c381386098
commit 39c952f8eb
2 changed files with 68 additions and 53 deletions

View File

@ -1,59 +1,67 @@
use rocket::{http::Status, outcome, request::{FromRequest, Outcome}, Request, State}; use rocket::{Request, State, Outcome};
use templates::context::Context; use rocket::http::Status;
use rocket::request::{self, FromRequest};
/// The TemplateEngine type: implements `FromRequest`, allowing you to communicate use templates::Context;
/// directly with the template engines.
/// /// The `TemplateMetadata` type: implements `FromRequest`, allowing dynamic
/// Using it in a request handler always returns successfully except when the [`Template::fairing()`] /// queries about template metadata.
/// wasn't attached to rocket.
/// ///
/// # Usage /// # Usage
/// ///
/// Ensure that the template [fairing](/rocket/fairing/) is attached to /// First, ensure that the template [fairing](`rocket::fairing`) is attached to
/// your Rocket application: /// your Rocket application:
/// ///
/// ```rust /// ```rust
/// extern crate rocket; /// # extern crate rocket;
/// extern crate rocket_contrib; /// # extern crate rocket_contrib;
/// /// #
/// use rocket_contrib::Template; /// use rocket_contrib::Template;
/// ///
/// fn main() { /// fn main() {
/// rocket::ignite() /// rocket::ignite()
/// // ...
/// .attach(Template::fairing()) /// .attach(Template::fairing())
/// // ... /// // ...
/// # ; /// # ;
/// } /// }
/// ``` /// ```
/// ///
/// The `TemplateEngine` type implements Rocket's `FromRequest` trait, so it can be /// The `TemplateMetadata` type implements Rocket's `FromRequest` trait, so it can
/// used as Parameter in a request handler: /// be used as a request guard in any request handler.
///
/// ```rust
/// # #![feature(plugin, decl_macro)]
/// # #![plugin(rocket_codegen)]
/// # extern crate rocket;
/// # #[macro_use] extern crate rocket_contrib;
/// # fn main() { }
/// #
/// use rocket_contrib::{Template, TemplateMetadata};
/// ///
/// ```rust,ignore
/// #[get("/")] /// #[get("/")]
/// fn homepage(engine: TemplateEngine) -> Template { /// fn homepage(metadata: TemplateMetadata) -> Template {
/// if engine.template_exists("specific") { /// // Conditionally render a template if it's available.
/// return Template::render("specfic", json!({})); /// if metadata.contains_template("some-template") {
/// Template::render("some-template", json!({ /* .. */ }))
/// } else {
/// Template::render("fallback", json!({ /* .. */ }))
/// } /// }
/// Template::render("fallback", json!({}))
/// } /// }
/// ``` /// ```
pub struct TemplateMetadata<'a>(&'a Context); pub struct TemplateMetadata<'a>(&'a Context);
impl<'a> TemplateMetadata<'a> { impl<'a> TemplateMetadata<'a> {
/// Returns `true` if the template with name `name` was loaded at start-up time. Otherwise, /// Returns `true` if the template with name `name` was loaded at start-up
/// returns `false`. /// time. Otherwise, returns `false`.
/// ///
/// # Example /// # Example
/// ///
/// ```rust,ignore /// ```rust
/// #[get("/")] /// use rocket_contrib::TemplateMetadata;
/// fn homepage(engine: TemplateEngine) -> Template { ///
/// if engine.template_exists("specific") { /// fn handler(metadata: TemplateMetadata) {
/// return Template::render("specfic", json!({})); /// // Returns `true` if the template with name `"name"` was loaded.
/// } /// let loaded = metadata.contains_template("name");
/// Template::render("fallback", json!({}))
/// } /// }
/// ``` /// ```
pub fn contains_template(&self, name: &str) -> bool { pub fn contains_template(&self, name: &str) -> bool {
@ -61,19 +69,21 @@ impl<'a> TemplateMetadata<'a> {
} }
} }
/// Retrieves the template metadata. If a template fairing hasn't been attached,
/// an error is printed and an empty `Err` with status `InternalServerError`
/// (`500`) is returned.
impl<'a, 'r> FromRequest<'a, 'r> for TemplateMetadata<'a> { impl<'a, 'r> FromRequest<'a, 'r> for TemplateMetadata<'a> {
type Error = (); type Error = ();
fn from_request(request: &'a Request) -> Outcome<Self, ()> { fn from_request(request: &'a Request) -> request::Outcome<Self, ()> {
request request.guard::<State<Context>>()
.guard::<State<Context>>()
.succeeded() .succeeded()
.and_then(|ctxt| Some(outcome::Outcome::Success(TemplateMetadata(ctxt.inner())))) .and_then(|ctxt| Some(Outcome::Success(TemplateMetadata(ctxt.inner()))))
.unwrap_or_else(|| { .unwrap_or_else(|| {
error_!("Uninitialized template context: missing fairing."); error_!("Uninitialized template context: missing fairing.");
info_!("To use templates, you must attach `Template::fairing()`."); info_!("To use templates, you must attach `Template::fairing()`.");
info_!("See the `Template` documentation for more information."); info_!("See the `Template` documentation for more information.");
outcome::Outcome::Failure((Status::InternalServerError, ())) Outcome::Failure((Status::InternalServerError, ()))
}) })
} }
} }

View File

@ -6,15 +6,19 @@ extern crate rocket_contrib;
#[cfg(feature = "templates")] #[cfg(feature = "templates")]
mod templates_tests { 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::env;
use std::path::PathBuf; use std::path::PathBuf;
use rocket::{Rocket, http::RawStr};
use rocket::config::{Config, Environment};
use rocket_contrib::{Template, TemplateMetadata};
#[get("/<engine>/<name>")] #[get("/<engine>/<name>")]
fn contains_template(template_metadata: TemplateMetadata, engine: &RawStr, name: &RawStr) -> Plain<String> { fn template_check(md: TemplateMetadata, engine: &RawStr, name: &RawStr) -> Option<()> {
Plain(template_metadata.contains_template(&format!("{}/{}", engine, name)).to_string()) match md.contains_template(&format!("{}/{}", engine, name)) {
true => Some(()),
false => None
}
} }
fn template_root() -> PathBuf { fn template_root() -> PathBuf {
@ -28,7 +32,7 @@ mod templates_tests {
.expect("valid configuration"); .expect("valid configuration");
::rocket::custom(config).attach(Template::fairing()) ::rocket::custom(config).attach(Template::fairing())
.mount("/", routes![contains_template]) .mount("/", routes![template_check])
} }
#[cfg(feature = "tera_templates")] #[cfg(feature = "tera_templates")]
@ -60,20 +64,20 @@ mod templates_tests {
} }
#[test] #[test]
fn test_template_engine_with_tera() { fn test_template_metadata_with_tera() {
let client = Client::new(rocket()).unwrap(); let client = Client::new(rocket()).unwrap();
let mut response = client.get("/tera/txt_test").dispatch(); let response = client.get("/tera/txt_test").dispatch();
assert_eq!(response.status(), Status::Ok); assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().unwrap().into_string().unwrap(), "true");
let mut response = client.get("/tera/html_test").dispatch(); let response = client.get("/tera/html_test").dispatch();
assert_eq!(response.status(), Status::Ok); assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().unwrap().into_string().unwrap(), "true");
let mut response = client.get("/tera/not_existing").dispatch(); let response = client.get("/tera/not_existing").dispatch();
assert_eq!(response.status(), Status::Ok); assert_eq!(response.status(), Status::NotFound);
assert_eq!(response.body().unwrap().into_string().unwrap(), "false");
let response = client.get("/hbs/txt_test").dispatch();
assert_eq!(response.status(), Status::NotFound);
} }
} }
@ -100,16 +104,17 @@ mod templates_tests {
} }
#[test] #[test]
fn test_template_engine_with_handlebars() { fn test_template_metadata_with_handlebars() {
let client = Client::new(rocket()).unwrap(); let client = Client::new(rocket()).unwrap();
let mut response = client.get("/hbs/test").dispatch(); let response = client.get("/hbs/test").dispatch();
assert_eq!(response.status(), Status::Ok); assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().unwrap().into_string().unwrap(), "true");
let mut response = client.get("/hbs/not_existing").dispatch(); let response = client.get("/hbs/not_existing").dispatch();
assert_eq!(response.status(), Status::Ok); assert_eq!(response.status(), Status::NotFound);
assert_eq!(response.body().unwrap().into_string().unwrap(), "false");
let response = client.get("/tera/test").dispatch();
assert_eq!(response.status(), Status::NotFound);
} }
} }
} }