Use Template Engine

Salvo doesn't have a templating engine built in; after all, the style of templating you like to use varies from person to person.

A template engine is essentially: data + template = string.

So, any template engine can be supported as long as it can render the final string.

For example, we can use askama like so:

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("127.0.0.1:5800").bind().await;
    Server::new(acceptor).serve(router).await;
}
[package]
name = "example-template-askama"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
askama = "0.11"
salvo.workspace = true
tokio = { version = "1", features = ["macros"] }
tracing = "0.1"
tracing-subscriber = "0.3"
Hello, {{ name }}!