使用模板引擎

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应用的开发趋势。