Tera renders HTML templates for server-side Rust applications. An Actix Web handler supplies data, renders a template, and returns the resulting HTML in an HTTP response. The page can keep its static markup while changing values for each request. section 7.3 section 7.8
A minimal rendering path has three parts:
- Put an HTML template under `static/iter1`; `{{ name }}` marks where a context value appears. section 7.3
- Load templates with `Tera::new(...)` in `main` and add the instance to Actix application state. section 7.3
- In the handler, create a `tera::Context`, insert `name`, call `render("index.html", &ctx)`, and return the string as `text/html`. Convert a render failure into a server error. section 7.3
async fn index(tmpl: web::Data<tera::Tera>) -> Result<HttpResponse, Error> {
let mut ctx = tera::Context::new(); #1
ctx.insert("name", "Bob"); #2
let s = tmpl
.render("index.html", &ctx) #3
.map_err(|_| error::ErrorInternalServerError("Template error"))?;
Ok(HttpResponse::Ok().content_type("text/html").body(s)) #4
}
The index handler shows the complete context-to-HTTP-response path, including render-error handling. section 7.3
Templates also handle repeated content. Insert a vector of tutors under `tutors`, then use `{% for tutor in tutors %}` and `{{ tutor.name }}` to produce a list item for each tutor. The demonstrated list starts with hardcoded data; the same page can receive data obtained from a web service. section 7.5 section 7.8
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Actix web</title>
</head>
<body>
<h1>Tutors list</h1>
<ol> #1
{% for tutor in tutors %} #2
<li> #3
<h5>{{tutor.name}}</h5> #4
</li>
{% endfor %} #5
</ol>
</body>
</html>
The list template shows how a Tera `for` block surrounds ordinary HTML and accesses a field on each item. section 7.5
For forms, render an input page, receive its POST data through Actix’s `web::Form<T>` extractor, and insert submitted values into a context for the response page. When validation fails, a handler can instead re-render the form template with an error message. Template variables therefore support both displayed data and feedback beside user input. section 7.4 section 8.4
