mirror of
https://github.com/actix/examples
synced 2025-06-26 17:17:42 +02:00
restructure folders
This commit is contained in:
9
templating/tera/Cargo.toml
Normal file
9
templating/tera/Cargo.toml
Normal file
@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "template-tera"
|
||||
version = "1.0.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
env_logger = "0.9.0"
|
||||
tera = "1.8.0"
|
||||
actix-web = "4.0.0-beta.21"
|
18
templating/tera/README.md
Normal file
18
templating/tera/README.md
Normal file
@ -0,0 +1,18 @@
|
||||
# template_tera
|
||||
|
||||
Minimal example of using the template [tera](https://github.com/Keats/tera) that displays a form.
|
||||
|
||||
## Usage
|
||||
|
||||
### server
|
||||
|
||||
```bash
|
||||
cd template_engines/tera
|
||||
cargo run (or ``cargo watch -x run``)
|
||||
# Started http server: 127.0.0.1:8080
|
||||
```
|
||||
|
||||
### web client
|
||||
|
||||
- [http://localhost:8080](http://localhost:8080)
|
||||
- [http://localhost:8080/non-existing-page](http://localhost:8080/non-existing-page) - 404 page rendered using template
|
93
templating/tera/src/main.rs
Normal file
93
templating/tera/src/main.rs
Normal file
@ -0,0 +1,93 @@
|
||||
use actix_web::body::BoxBody;
|
||||
use actix_web::dev::ServiceResponse;
|
||||
use actix_web::http::header::ContentType;
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::middleware::{ErrorHandlerResponse, ErrorHandlers};
|
||||
use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer, Result};
|
||||
use std::collections::HashMap;
|
||||
use tera::Tera;
|
||||
|
||||
// store tera template in application state
|
||||
async fn index(
|
||||
tmpl: web::Data<tera::Tera>,
|
||||
query: web::Query<HashMap<String, String>>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let s = if let Some(name) = query.get("name") {
|
||||
// submitted form
|
||||
let mut ctx = tera::Context::new();
|
||||
ctx.insert("name", &name.to_owned());
|
||||
ctx.insert("text", &"Welcome!".to_owned());
|
||||
tmpl.render("user.html", &ctx)
|
||||
.map_err(|_| error::ErrorInternalServerError("Template error"))?
|
||||
} else {
|
||||
tmpl.render("index.html", &tera::Context::new())
|
||||
.map_err(|_| error::ErrorInternalServerError("Template error"))?
|
||||
};
|
||||
Ok(HttpResponse::Ok().content_type("text/html").body(s))
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
std::env::set_var("RUST_LOG", "actix_web=info");
|
||||
env_logger::init();
|
||||
|
||||
println!("Listening on: 127.0.0.1:8080, open browser and visit have a try!");
|
||||
HttpServer::new(|| {
|
||||
let tera =
|
||||
Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap();
|
||||
|
||||
App::new()
|
||||
.app_data(web::Data::new(tera))
|
||||
.wrap(middleware::Logger::default()) // enable logger
|
||||
.service(web::resource("/").route(web::get().to(index)))
|
||||
.service(web::scope("").wrap(error_handlers()))
|
||||
})
|
||||
.bind(("127.0.0.1", 8080))?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
||||
// Custom error handlers, to return HTML responses when an error occurs.
|
||||
fn error_handlers() -> ErrorHandlers<BoxBody> {
|
||||
ErrorHandlers::new().handler(StatusCode::NOT_FOUND, not_found)
|
||||
}
|
||||
|
||||
// Error handler for a 404 Page not found error.
|
||||
fn not_found<B>(res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<BoxBody>> {
|
||||
let response = get_error_response(&res, "Page not found");
|
||||
Ok(ErrorHandlerResponse::Response(ServiceResponse::new(
|
||||
res.into_parts().0,
|
||||
response.map_into_left_body(),
|
||||
)))
|
||||
}
|
||||
|
||||
// Generic error handler.
|
||||
fn get_error_response<B>(res: &ServiceResponse<B>, error: &str) -> HttpResponse {
|
||||
let request = res.request();
|
||||
|
||||
// Provide a fallback to a simple plain text response in case an error occurs during the
|
||||
// rendering of the error page.
|
||||
let fallback = |e: &str| {
|
||||
HttpResponse::build(res.status())
|
||||
.content_type(ContentType::plaintext())
|
||||
.body(e.to_string())
|
||||
};
|
||||
|
||||
let tera = request.app_data::<web::Data<Tera>>().map(|t| t.get_ref());
|
||||
match tera {
|
||||
Some(tera) => {
|
||||
let mut context = tera::Context::new();
|
||||
context.insert("error", error);
|
||||
context.insert("status_code", res.status().as_str());
|
||||
let body = tera.render("error.html", &context);
|
||||
|
||||
match body {
|
||||
Ok(body) => HttpResponse::build(res.status())
|
||||
.content_type(ContentType::html())
|
||||
.body(body),
|
||||
Err(_) => fallback(error),
|
||||
}
|
||||
}
|
||||
None => fallback(error),
|
||||
}
|
||||
}
|
10
templating/tera/templates/error.html
Normal file
10
templating/tera/templates/error.html
Normal file
@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>{{ error }}</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>{{ status_code }} {{ error }}</h1>
|
||||
</body>
|
||||
</html>
|
17
templating/tera/templates/index.html
Normal file
17
templating/tera/templates/index.html
Normal file
@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Actix Web</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Welcome!</h1>
|
||||
<p>
|
||||
<h3>What is your name?</h3>
|
||||
<form>
|
||||
<input type="text" name="name" /><br/>
|
||||
<p><input type="submit"></p>
|
||||
</form>
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
13
templating/tera/templates/user.html
Normal file
13
templating/tera/templates/user.html
Normal file
@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Actix Web</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hi, {{ name }}!</h1>
|
||||
<p>
|
||||
{{ text }}
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
Reference in New Issue
Block a user