使用模板引擎
Salvo 没有内置任何模板引擎, 毕竟, 喜欢使用那种风格的模板引擎, 因人而异.
模板引擎本质上就是: 数据 + 模板 = 字符串.
所以, 只要能渲染最终的字符串就可以支持任意的模板引擎.
比如对 askama
的支持:
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 }}!