使用模板引擎
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 }}!