1
0
mirror of https://github.com/actix/examples synced 2025-09-02 03:46:38 +02:00

Refactor template yarte example for use bytes implementation (#392)

This commit is contained in:
Juan Aguilar
2020-12-17 22:34:40 +01:00
committed by GitHub
parent 47d4067498
commit 401753dd90
5 changed files with 267 additions and 167 deletions

View File

@@ -8,10 +8,12 @@ edition = "2018"
[dependencies]
actix-web = "3"
env_logger = "0.8"
yarte = { version = "0.13", features = ["html-min"] }
# TODO: remove fixed feature. Is a bug.
yarte = { version = "0.12", features = ["bytes-buf", "html-min", "fixed"] }
derive_more = "0.99"
[build-dependencies.yarte_helpers]
version = "0.8"
version = "0.12"
default-features = false
features = ["config"]

View File

@@ -2,67 +2,9 @@
Minimal example of using template [yarte](https://github.com/botika/yarte) that displays a form.
[Template benchmarks in stable](https://github.com/botika/template-bench-rs)
```bash
cargo test
cargo run
```
> open `localhost:8080`
## Generated code
```rust
impl ::std::fmt::Display for IndexTemplate {
fn fmt(&self, _fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
_fmt.write_str(
"<!DOCTYPE html><html><head><meta charset=\"utf-8\" /><title>Actix \
web</title></head><body>",
)?;
if let Some(name__0) = self.query.get("name") {
let lastname__1 = self.query.get("lastname").ok_or(yarte::Error)?;
_fmt.write_str("<h1>Hi, ")?;
::yarte::Render::render(&(name__0), _fmt)?;
_fmt.write_str(" ")?;
::yarte::Render::render(&(lastname__1), _fmt)?;
_fmt.write_str("!</h1><p id=\"hi\" class=\"welcome\">Welcome</p>")?;
} else {
_fmt.write_str(
"<h1 id=\"welcome\" class=\"welcome\">Welcome!</h1><div><h3>What is your \
name?</h3><form>Name: <input type=\"text\" name=\"name\" /><br/>Last name: \
<input type=\"text\" name=\"lastname\" /><br/><p><input \
type=\"submit\"></p></form></div>",
)?;
}
_fmt.write_str("</body></html>")?;
Ok(())
}
}
impl ::yarte::Template for IndexTemplate {
fn mime() -> &'static str {
"text/html; charset=utf-8"
}
fn size_hint() -> usize {
838usize
}
}
impl ::yarte::aw::Responder for IndexTemplate {
type Error = ::yarte::aw::Error;
type Future = ::yarte::aw::Ready<::std::result::Result<::yarte::aw::HttpResponse, Self::Error>>;
#[inline]
fn respond_to(self, _req: &::yarte::aw::HttpRequest) -> Self::Future {
match self.call() {
Ok(body) => ::yarte::aw::ok(
::yarte::aw::HttpResponse::Ok()
.content_type(Self::mime())
.body(body),
),
Err(_) => ::yarte::aw::err(::yarte::aw::ErrorInternalServerError("Some error message")),
}
}
}
```

View File

@@ -1,29 +1,28 @@
use std::collections::HashMap;
use actix_web::{
error::ErrorInternalServerError, get, middleware::Logger, web, App, Error,
HttpResponse, HttpServer,
get, middleware::Logger, web, App, Error, HttpResponse, HttpServer, ResponseError,
};
use yarte::TemplateMin;
use derive_more::Display;
use yarte::ywrite_min;
#[derive(TemplateMin)]
#[template(path = "index")]
struct IndexTemplate {
query: web::Query<HashMap<String, String>>,
}
#[derive(Debug, Display)]
struct MyErr(pub &'static str);
impl ResponseError for MyErr {}
#[get("/")]
async fn index(
query: web::Query<HashMap<String, String>>,
) -> Result<HttpResponse, Error> {
IndexTemplate { query }
.call()
.map(|body| {
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(body)
})
.map_err(|_| ErrorInternalServerError("Some error message"))
let mut body = web::BytesMut::with_capacity(512);
// `ywrite_min` is work in progress check your templates before put in production
// or use `ywrite_html`
ywrite_min!(body, "{{> index }}");
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(body))
}
#[actix_web::main]
@@ -40,9 +39,10 @@ async fn main() -> std::io::Result<()> {
#[cfg(test)]
mod test {
use super::*;
use actix_web::{http, test as atest, web::Bytes};
use super::*;
#[actix_rt::test]
async fn test() {
let mut app = atest::init_service(App::new().service(index)).await;
@@ -98,7 +98,7 @@ mod test {
let bytes = atest::read_body(resp).await;
assert_eq!(bytes, Bytes::from_static("Some error message".as_ref()));
assert_eq!(bytes, Bytes::from_static("Bad query".as_ref()));
let req = atest::TestRequest::with_uri("/?lastname=bar").to_request();
let resp = atest::call_service(&mut app, req).await;

View File

@@ -1,6 +1,6 @@
{{#> base title = "Actix web" }}
{{~#if let Some(name) = query.get("name") }}
{{ let lastname = query.get("lastname").ok_or(yarte::Error)? }}
{{ let lastname = query.get("lastname").ok_or(MyErr("Bad query"))? }}
{{> card/hi ~}}
{{ else ~}}
{{> card/form ~}}