Skip to content

Commit

Permalink
Add templating example with tera (#267)
Browse files Browse the repository at this point in the history
  • Loading branch information
milesgranger authored and yoshuawuyts committed Jun 6, 2019
1 parent 1fb4ab3 commit 4486ba0
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ mime = "0.3.13"
mime_guess = "2.0.0-alpha.6"
percent-encoding = "1.0.1"
serde = { version = "1.0.91", features = ["derive"] }
tera = "0.11"
tide-log = { path = "./tide-log" }
env_logger = "0.6.1"
log4rs = "0.8.3"
Expand Down
15 changes: 15 additions & 0 deletions examples/templates/tera-hello-world.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<html>
<head>
<title>{{ page_title }}</title>
</head>

<body>
<ul>
{% for point in points %}
<li>
{{ point }}
</li>
{% endfor %}
</ul>
</body>
</html>
53 changes: 53 additions & 0 deletions examples/templating_tera.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#![feature(async_await)]

use tera::{self, compile_templates};
use tide::{self, App, Context, EndpointResult, Error};

// AppState to pass with context and will hold
// the interface to the tera rendering engine
struct AppState {
template: tera::Tera,
}

// Render some data into the 'tera-hello-world.html template in examples/templates directory
async fn index(ctx: Context<AppState>) -> EndpointResult {
// Create the context for the template
let mut context = tera::Context::new();
context.insert("page_title", "Hello from Tera templating!");
context.insert("points", &vec!["point1", "point2"]);

// Render the variables into the template
let s = ctx
.state()
.template
.render("tera-hello-world.html", &context)
.map_err(|err| {
// Map the tera::Error into a Tide error
let resp = http::Response::builder()
.status(500)
.body(err.description().into())
.unwrap();
Error::from(resp)
})?;

// Build normal response, putting the rendered string into bytes -> Body
let resp = http::Response::builder()
.header(http::header::CONTENT_TYPE, mime::TEXT_HTML.as_ref())
.status(http::StatusCode::OK)
.body(s.as_bytes().into())
.expect("Failed to build response");
Ok(resp)
}

fn main() -> Result<(), std::io::Error> {
let template_dir = format!("{}/examples/templates/*", env!("CARGO_MANIFEST_DIR"));

let state = AppState {
template: compile_templates!(&template_dir),
};

let mut app = App::with_state(state);
app.at("/").get(index);
app.run("127.0.0.1:8000")?;
Ok(())
}

0 comments on commit 4486ba0

Please sign in to comment.