服务端模板
属于 kxed 全栈 Rust 后端框架生态:官网 | 在线文档 | 源码仓库 | 主包 crates.io
基于 MiniJinja 提供服务端 HTML / XML / 文本模板渲染,默认对 .html、.htm 与 .xml 开启防 XSS 自动转义,支持定制全站浏览器 4xx/5xx 错误页、表单校验失败回显以及开发期目录热重载。实战配合见 多语言、模板与 SSE 教程。
快速接入#
在 Cargo.toml 开启主包 kxed 的 templates 特性(本地开发需要改模板即刻生效时改开 templates-autoreload;独立组装可依赖 kxed-plugins = { version = "0.0.5-alpha", features = ["templates"] }):
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["templates"] }在应用配置文件中指定模板目录(默认即为 "templates"):
[templates]
dir = "templates"在模板目录下新建 home.html 后,注册 TemplatesPlugin::new() 并在路由中调用 ctx.render_template 返回 HTML 响应:
use kxed::plugins::templates::{Rendered, TemplatesPlugin};
use kxed::prelude::*;
use serde_json::json;
async fn home(ctx: AppCtx) -> Result<Rendered, AppErr> {
ctx.render_template("home.html", json!({ "user": "Ada" }))
}
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.plugin(TemplatesPlugin::new())
.routes(|router| {
router.route("/", get(home));
})
.run()
.await
}核心用法#
模板渲染与自定义过滤器#
可通过 .with_env(|env| ..) 注册自定义 MiniJinja 过滤器、全局函数与常量:
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::templates::{AppCtxTemplates, Rendered, TemplatesPlugin};
async fn home(ctx: AppCtx) -> Result<Rendered, AppErr> {
ctx.render_template("home.html", serde_json::json!({ "user": "ada" }))
}
let plugin = TemplatesPlugin::new().with_env(|env| {
env.add_filter("shout", |value: String| value.to_uppercase());
});模板扩展名(先剥离可选的 .j2 / .jinja / .jinja2 后缀)同时决定自动转义策略与响应 Content-Type(不可在 with_env 中覆盖转义回调,防止 HTML 内容以未转义形式下发):
| 最终扩展名 | 自动转义策略 | 响应 Content-Type |
|---|---|---|
.html、.htm | 开启 HTML 转义 | text/html; charset=utf-8 |
.xml | 开启 HTML/XML 转义 | application/xml; charset=utf-8 |
其他(.txt 等) | 不转义 | text/plain; charset=utf-8 |
错误页#
传统服务端渲染站点调用 TemplatesPlugin::new().with_error_pages("errors") 后,当浏览器页面请求(Accept 首选 text/html)触发 4xx 或 5xx 错误时,自动在 HttpStage::ErrorPages 将默认 JSON 错误体替换为 templates/errors/<status>.html(不存在则回退渲染 4xx.html 或 5xx.html),API 与 fetch 请求仍原样返回 JSON:
<h1>{{ status }}</h1>
{% if code == "not_found" %}<p>您访问的页面不存在。</p>{% endif %}
<p>请求追踪号:{{ request_id }}</p>- 安全脱敏与响应头保留:模板仅注入
status、code与request_id三个变量(不注入内部message,防止泄露 5xx 堆栈或内部信息),并完整保留原响应的状态码、Set-Cookie、Retry-After、WWW-Authenticate及追加Vary: Accept。建议保持errors/429.html简洁无复杂嵌套,降低限流拦截时的渲染开销。 - 宿主底层直返豁免:进程级 panic 500、请求超时 504/408、宿主级
server.http.max_body_bytes413 与停机/维护模式 503 由底层准入层直接返回,不经过模板替换。
表单校验失败后重渲染#
HTML 表单提交校验失败后需要带着原输入值与字段错误提示重绘页面时,使用 Form<T> 提取输入并手动调用 validate()(或配合 PRG 重定向模式调用 Session::flash_input,自动脱敏含 password 的字段,见 Session 闪存与表单回显):
use axum::response::{IntoResponse, Redirect, Response};
use garde::Validate;
use kxed_core::{validation_error, AppCtx, AppErr, Form, StatusCode};
use kxed_plugins::templates::AppCtxTemplates;
use std::collections::BTreeMap;
#[derive(serde::Deserialize, serde::Serialize, garde::Validate)]
struct Signup {
#[garde(length(min = 3, max = 32))]
username: String,
}
async fn signup(ctx: AppCtx, Form(input): Form<Signup>) -> Result<Response, AppErr> {
let Err(report) = input.validate() else {
return Ok(Redirect::to("/welcome").into_response());
};
let mut errors: BTreeMap<String, Vec<String>> = BTreeMap::new();
for violation in validation_error(&report).violations() {
errors.entry(violation.field().to_owned()).or_default().push(violation.message().to_owned());
}
let page = ctx.render_template("signup.html", serde_json::json!({ "errors": errors, "old": input }))?;
Ok((StatusCode::UNPROCESSABLE_ENTITY, page).into_response())
}Config#
| key | default | contract |
|---|---|---|
templates.dir | templates | 模板根目录路径(不存在时预检与启动直接报错;多实例集群内必须一致) |
templates.autoreload | false | 设为 true 时后台线程每 250ms 扫描目录变更并在下次渲染前自动重建模板环境(需开启 templates-autoreload 特性,仅限本地开发使用) |