Skip to main content

HTML

Rendering HTML pages

Actix 4.9+ 5 min read

# HTML Responses

While Actix Web is often used for APIs, it can also serve traditional HTML pages.

#Sending HTML Strings

If you return a raw string containing HTML, you must explicitly set the Content-Type, otherwise browsers will display it as plain text.

code_blocksrust
use actix_web::{get, HttpResponse, Responder};

#[get("/")]
async fn index() -> impl Responder {
    HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")
        .body("<h1>Hello World</h1>")
}

#HTML Templating

For dynamic HTML, you integrate template engines like Askama, Tera, or Handlebars. You render the template to a string and return it as the body of an HttpResponse.

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{get, App, HttpServer, HttpResponse, Responder};
2
3#[get("/")]
4async fn home() -> impl Responder {
5 let html = "<html><body><h1>Welcome!</h1></body></html>";
6 HttpResponse::Ok()
7 .content_type("text/html; charset=utf-8")
8 .body(html)
9}
10
11#[actix_web::main]
12async fn main() -> std::io::Result<()> {
13 HttpServer::new(|| App::new().service(home))
14 .bind(("127.0.0.1", 8080))?
15 .run()
16 .await
17}
Was this page helpful?