使用模板引擎

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

模板引擎的核心原理其實就是:數據 + 模板 = 字符串。

因此,只要能渲染出最終字符串結果,理論上可以支援任何模板引擎。

以下是以 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;
}

注意事項:若非特別複雜的專案,我們更推薦採用前後端分離的開發模式。使用生態更完善、靈活性更高的前端框架(如 React、Vue、Svelte 等)來構建前端界面,而 Salvo 則專注於後端 API 服務。這種架構不僅開發效率更高,前後端職責劃分更清晰,也更符合現代 Web 應用的開發潮流。