mirror of https://github.com/rwf2/Rocket.git
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:
parent
5e2502f028
commit
c381386098
|
@ -37,5 +37,8 @@ handlebars = { version = "0.32", optional = true }
|
||||||
glob = { version = "^0.2", optional = true }
|
glob = { version = "^0.2", optional = true }
|
||||||
tera = { version = "0.11", optional = true }
|
tera = { version = "0.11", optional = true }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
rocket_codegen = { version = "0.4.0-dev", path = "../../core/codegen" }
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
all-features = true
|
all-features = true
|
||||||
|
|
|
@ -74,7 +74,7 @@ pub use msgpack::{MsgPack, MsgPackError};
|
||||||
mod templates;
|
mod templates;
|
||||||
|
|
||||||
#[cfg(feature = "templates")]
|
#[cfg(feature = "templates")]
|
||||||
pub use templates::{Template, Engines};
|
pub use templates::{Engines, Template, TemplateMetadata};
|
||||||
|
|
||||||
#[cfg(feature = "uuid")]
|
#[cfg(feature = "uuid")]
|
||||||
mod uuid;
|
mod uuid;
|
||||||
|
|
|
@ -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, ()))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
|
@ -6,8 +6,10 @@ extern crate glob;
|
||||||
#[cfg(feature = "handlebars_templates")] mod handlebars_templates;
|
#[cfg(feature = "handlebars_templates")] mod handlebars_templates;
|
||||||
mod engine;
|
mod engine;
|
||||||
mod context;
|
mod context;
|
||||||
|
mod metadata;
|
||||||
|
|
||||||
pub use self::engine::Engines;
|
pub use self::engine::Engines;
|
||||||
|
pub use self::metadata::TemplateMetadata;
|
||||||
|
|
||||||
use self::engine::Engine;
|
use self::engine::Engine;
|
||||||
use self::context::Context;
|
use self::context::Context;
|
||||||
|
|
|
@ -1,14 +1,21 @@
|
||||||
|
#![feature(plugin, decl_macro)]
|
||||||
|
#![plugin(rocket_codegen)]
|
||||||
|
|
||||||
extern crate rocket;
|
extern crate rocket;
|
||||||
extern crate rocket_contrib;
|
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;
|
#[get("/<engine>/<name>")]
|
||||||
use rocket::config::{Config, Environment};
|
fn contains_template(template_metadata: TemplateMetadata, engine: &RawStr, name: &RawStr) -> Plain<String> {
|
||||||
use rocket_contrib::Template;
|
Plain(template_metadata.contains_template(&format!("{}/{}", engine, name)).to_string())
|
||||||
|
}
|
||||||
|
|
||||||
fn template_root() -> PathBuf {
|
fn template_root() -> PathBuf {
|
||||||
let cwd = env::current_dir().expect("current working directory");
|
let cwd = env::current_dir().expect("current working directory");
|
||||||
|
@ -21,12 +28,15 @@ 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])
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "tera_templates")]
|
#[cfg(feature = "tera_templates")]
|
||||||
mod tera_tests {
|
mod tera_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use rocket::http::Status;
|
||||||
|
use rocket::local::Client;
|
||||||
|
|
||||||
const UNESCAPED_EXPECTED: &'static str
|
const UNESCAPED_EXPECTED: &'static str
|
||||||
= "\nh_start\ntitle: _test_\nh_end\n\n\n<script />\n\nfoot\n";
|
= "\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);
|
let template = Template::show(&rocket, "tera/html_test", &map);
|
||||||
assert_eq!(template, Some(ESCAPED_EXPECTED.into()));
|
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")]
|
#[cfg(feature = "handlebars_templates")]
|
||||||
mod handlebars_tests {
|
mod handlebars_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use rocket::http::Status;
|
||||||
|
use rocket::local::Client;
|
||||||
|
|
||||||
const EXPECTED: &'static str
|
const EXPECTED: &'static str
|
||||||
= "Hello _test_!\n\n<main> <script /> hi </main>\nDone.\n\n";
|
= "Hello _test_!\n\n<main> <script /> hi </main>\nDone.\n\n";
|
||||||
|
@ -69,5 +98,18 @@ mod templates_tests {
|
||||||
let template = Template::show(&rocket, "hbs/test", &map);
|
let template = Template::show(&rocket, "hbs/test", &map);
|
||||||
assert_eq!(template, Some(EXPECTED.into()));
|
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");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue