I wanted to make an auxiliary function for rendering templates in actix, here's how it looks:
fn render_response(
tera: web::Data<Tera>,
template_name: &str,
context: &Context,
) -> impl Responder {
match tera.render(template_name, context) {
Ok(rendered) => HttpResponse::Ok().body(rendered),
Err(_) => HttpResponse::InternalServerError().body("Failed to resolve the template."),
}
}
I'm using it in views like this one below:
async fn signup(tera: web::Data<Tera>) -> impl Responder {
let mut data = Context::new();
data.insert("title", "Sign Up");
render_response(tera, "signup.html", &data)
}
If the view is as simple as the one above, everything works fine, but if the view is slightly more complicated I get a problem:
async fn login(tera: web::Data<Tera>, id: Identity) -> impl Responder {
let mut data = Context::new();
data.insert("title", "Login");
if let Some(id) = id.identity() {
return HttpResponse::Ok().body(format!("Already logged in: {}.", id));
}
render_response(tera, "login.html", &data)
}
The error I get:
error[E0308]: mismatched types
--> src\main.rs:101:5
|
42 | ) -> impl Responder {
| -------------- the found opaque type
...
101 | render_response(tera, "login.html", &data)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `actix_web::HttpResponse`, found opaque type
|
= note: expected type `actix_web::HttpResponse`
found opaque type `impl actix_web::Responder`
I've tried to extract the return HttpResponse...
to a separate function that also returns impl Responder
, but I'm getting different error now:
error[E0308]: mismatched types
--> src\main.rs:101:5
|
42 | ) -> impl Responder {
| -------------- the found opaque type
...
101 | render_response(tera, "login.html", &data)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected opaque type, found a different opaque type
|
= note: expected type `impl actix_web::Responder` (opaque type at <src\main.rs:104:28>)
found opaque type `impl actix_web::Responder` (opaque type at <src\main.rs:42:6>)
= note: distinct uses of `impl Trait` result in different opaque types
I don't really understand why it happens and how to fix it.