Using Template Engines

Salvo does not come with any built-in template engine, as preferences for template engine styles vary from person to person.

At its core, a template engine is simply: data + template = string.

Therefore, Salvo can support any template engine as long as it can render the final string.

For example, here's how to use askama:

main.rs
Cargo.toml
template/hello.toml
template-askama/src/main.rs
use askama::Template;
use salvo::prelude::*;

#[derive(Template)]
#[template(path = "hello.html")]
struct HelloTemplate<'a> {
name: &'a str,
}

#[handler]
async fn hello(req: &mut Request, res: &mut Response) {
let hello_tmpl = HelloTemplate {
    name: req.param::<&str>("name").unwrap_or("World"),
};
res.render(Text::Html(hello_tmpl.render().unwrap()));
}

#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();

let router = Router::with_path("{name}").get(hello);
let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
Server::new(acceptor).serve(router).await;
}

Note: For projects that aren't particularly complex, we highly recommend adopting a frontend-backend separation approach. Use more flexible and ecosystem-rich UI frameworks (such as React, Vue, Svelte, etc.) for frontend development, with Salvo serving as the backend API service. This approach offers higher development efficiency, clearer division of responsibilities between frontend and backend, and better aligns with modern web application development trends.