使用模板引擎

Salvo 並未內建任何模板引擎,畢竟每個人偏好的模板引擎風格各有不同。

模板引擎的本質可以歸納為:資料 + 模板 = 字串。

因此,只要能渲染出最終的字串,即可支援任意的模板引擎。

例如對 askama 的支援:

main.rs
Cargo.toml
templates/hello.html
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:8698").bind().await;
    Server::new(acceptor).serve(router).await;
}

注意:若非特別複雜的專案,我們更推薦採用前後端分離的開發方式,使用更靈活、生態更完善的 UI 框架(如 React、Vue、Svelte 等)來建構前端,並將 Salvo 作為後端 API 服務。這種方式不僅開發效率更高,前後端職責更清晰,也更符合現代 Web 應用的開發趨勢。