Topcoat `[page]` 完整指南:页面处理器、路径推导与视图组件复用
Topcoat #[page] 完整指南:页面处理器、路径推导与视图组件复用
在 Topcoat 中,一个页面并不是一个结构体或一个模板文件,而是一个被 #[page] 标注的 async 函数,它接收请求上下文并返回一个 View。理解这个宏如何处理路径、HTTP 方法、请求体与路由上下文,是写出可维护路由层的关键。本文以 docs/router/page.md 为主线,结合 topcoat-router 的宏语法实现、Page trait 与官方示例,逐层拆解 #[page] 的完整能力边界。
#[page] 的核心定位:页面即返回 View 的 async 函数
#<a href="https://link.gitcode.com/i/66d450bb827d0b2bf4113b4379841ac7" target="_blank">page] 是 topcoat-router 宏 crate 导出的属性宏,入口位于 [crates/topcoat-router/macro/src/lib.rs,其文档正文直接由 docs/page.md 引入。该宏最终展开为三部分:
- 一个带
#[component]标记的async fn,让页面本身可被view!当作组件调用; - 一个隐藏常量,其名称与函数同名,使
page_fn能作为一个“值”传给RouterBuilder::page; - 一个
impl Page(绝对路径)或impl ModulePage(模块推导路径),承载路径、方法、上下文与渲染逻辑。
运行时侧的抽象是 Page trait,它规定了页面必须提供的能力:
| 方法 | 作用 | 默认行为 |
|---|---|---|
id() |
处理器身份,用于判断“当前页”与 href! 解析 |
无默认值 |
methods() |
响应的 HTTP 方法集合 | 无默认值(宏展开为仅 GET) |
path() |
服务该页面的 URL 路径 | 无默认值 |
context() |
随页面携带的路由上下文值 | 返回空 ContextMap |
render(cx, body) |
在请求上下文下产出 BoxView |
无默认值 |
is_current(cx) |
当前请求是否命中了本页面 | 比较 route(cx).id() |
其中 is_current 的语义值得注意:它只比较处理器身份,因此路径参数取任何值、查询串或片段如何变化,都不影响判定结果,这使它天然适合导航栏高亮。文档同时注明,当请求未匹配任何路由时会 panic,所以调用前应确保处于已匹配的路由处理流程内。
三种路径声明:模块推导、相对路径与绝对路径
#<a href="https://link.gitcode.com/i/6941ebfa2e8795ca6b47f5117d0d7d91" target="_blank">page] 路径语法的解析逻辑在 [crates/topcoat-router/grammar/src/page.rs,路径字面量的归类与校验在 handler_path.rs。归纳起来共有三种写法:
无路径字符串:由模块决定 URL
// src/app/about.rs,位于 module_router!() 之下,服务 /about
use topcoat::{Result, context::Cx, router::page, view::{View, view}};
#[page]
async fn about(cx: &Cx) -> Result<impl View> {
Ok(view! { <h1>"About"</h1> })
}
此时宏生成的是 ModulePage 实现,包含 module_path()(返回 module_path!())与可选的 relative_path()。模块路由的映射规则见 docs/router/module.md:根模块映射到 /,每个子模块贡献一个路径段,静态模块名转换为 kebab-case(blog_posts → /blog-posts)。函数名不参与 URL 生成,因此同一模块内的两个模块推导处理器会得到相同路径,这一点在注册时需要格外留意。
./ 开头:在模块路径下扩展
// src/app/settings.rs,服务 /settings/export
#[page("./export")]
async fn export(cx: &Cx) -> Result<impl View> {
Ok(view! { <h1>"Export"</h1> })
}
HandlerPath::relative() 会去掉首个 .,把 ./export 变成 /export,再由模块路由器拼接到模块路径之后。宏语法层对此做了两项编译期约束:
"."会被拒绝,错误信息为a relative path must start with ./;".."或"../sibling"会被拒绝,错误信息为a relative path cannot leave the module path; use an absolute path starting with / instead。
"./" 是特例,它等价于模块路径加尾斜杠(/settings/),因为 relative() 返回的正是 /。尾斜杠在 Topcoat 中是有意义的:Path 用末尾的空 Static 段表示尾斜杠,/users/ 与 /users 是两个不同路径(见 crates/topcoat-router/src/path.rs)。至于请求了另一种形式时如何处理,docs/router.md 说明默认会重定向到声明的那一种,可通过 RouterBuilder::trailing_slash 调整。
/ 开头:绝对路径,独立于模块树
#[page("/users/{id}")]
async fn user_profile(cx: &Cx) -> Result<impl View> {
Ok(view! { <h1>"User profile"</h1> })
}
绝对路径会完全禁用模块推导,宏改为生成 impl Page,并且该处理器不会被 module_router!() 自动收集,必须显式注册。Path 支持四种段类型:静态段、{id} 参数段、{*rest} 通配段、(group) 逻辑分组段(转换为 matchit 路径时被剥离)。写入非法路径(例如缺少前导 /、出现 //)会在 Path::new 的常量求值阶段触发 panic,表现为编译错误。
三种写法对比如下:
| 写法 | 示例 | 是否被 module_router!() 收集 |
注册方式 |
|---|---|---|---|
| 无路径 | #[page] |
是 | 自动 |
./ 相对 |
#[page("./export")] |
是 | 自动 |
| 绝对 | #[page("/about")] |
否 | RouterBuilder::page 或 .discover() |
处理器签名:编译期强制的三条规则
PageItem::parse 对函数体做了严格校验(grammar/src/page.rs),三条规则会在编译期直接报错:
- 必须
async:否则报page functions must be async; - 必须声明返回类型:缺省返回类型报
page functions must declare a return type; - 第一个参数必须是
cx: &Cx:即使用不到也要写,因为组件模型、上下文读取与宏展开都依赖它。
第二个参数是可选请求体,实现 FromRequest,并且允许任意绑定模式:
// 形式一:直接绑定参数名
#[page]
async fn contact(cx: &Cx, body: Form<Search>) -> Result<impl View> {
Ok(view! { <main>"searching for " (body.q)</main> })
}
// 形式二:模式解构,例如 Form(input): Form<T>
#[page]
async fn contact(cx: &Cx, Form(input): Form<Search>) -> Result<impl View> {
Ok(view! { <main>"searching for " (input.q)</main> })
}
返回类型必须是 Result<impl View>。若返回中携带状态码或响应头,可参见 docs/router.md 中关于 StatusCode 与 HeaderMap 在 view! 中的用法。
宏在展开 render 时,对请求体做了如下处理:先调用 <T as FromRequest>::from_request(&cx, body).await?,解析失败会变成视图流产出的错误,与页面函数体返回错误等价;若没有第二个参数,则 drop(body)。这也意味着一个页面最多只有一个请求体参数,因为请求体只能被消费一次。
HTTP 方法声明:GET 是默认值
未声明方法时,宏固定生成:
Methods::Only(&[Method::GET])
因此“页面默认只响应 GET”并非框架运行时的猜测,而是宏展开的确定行为。需要其它方法时,按 #[route] 的同样形式声明:
#[page(POST)]
async fn signup(cx: &Cx, Form(input): Form<Signup>) -> Result<impl View> {
Ok(view! { <h1>"Welcome, " (input.email)</h1> })
}
支持的三种方法与路径的组合形态:
| 形态 | 示例 | 说明 |
|---|---|---|
| 单一方法 | #[page(POST)] |
只响应 POST |
| 方法列表 | #[page([GET, POST])] |
逐项响应 |
| 通配 | #[page(*)] |
响应所有方法 |
| 方法 + 路径 | #[page(POST "./export")] |
方法在前,路径紧随其后,无逗号 |
| 方法 + 路径 + 上下文 | #[page(POST "./export", with(Title("Export")))] |
前缀之后用逗号引出 with(...) |
两个容易踩的坑,测试用例已明确覆盖:
- 方法名必须大写,
#[page(get "/about")]与[GET, post]都会被拒绝; - 方法或路径与
with(...)之间必须有逗号,#[page("/about" with(a))]会导致解析失败;而纯粹的#[page(with(a))]不需要前导逗号,否则会被判定为“多余的逗号”。
当同一路径上同时存在具体方法与 * 时,具体方法优先(docs/router/module.md)。
路由上下文:让布局在页面运行前读到元数据
with(...) 是页面与布局、图层通信的机制。值在路由构建时初始化,因此外层布局可以在页面函数体执行之前读到页面声明的标题,这正是 <title> 这类头部标签能够正确渲染的原因。
use topcoat::{Result, context::{Cx, context}, router::{Slot, layout, page}, view::{View, view}};
struct Title(&'static str);
#[layout("/", with(Title("My shop")))]
async fn shell(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
let Title(title) = context::<Title>(cx);
Ok(view! {
<!DOCTYPE html>
<html>
<head><title>(title)</title></head>
<body>(slot)</body>
</html>
})
}
#[page("/products", with(Title("Products")))]
async fn products(cx: &Cx) -> Result<impl View> {
Ok(view! { <h1>"Products"</h1> })
}
可以连续写多个 with(...),用逗号分隔。上下文合并顺序在 docs/context.md 中有完整说明:路由构建器值 → 路由上下文 → 请求期 cx.with(...);同类值后者覆盖前者。路由上下文内部按嵌套顺序,先是图层(外到内),再是布局(外到内),最后是页面自身的值。被覆盖的值仍可通过 iter_context 按“最近优先”遍历,这让面包屑这类“收集各层贡献”的场景成为可能。
需要请求期数据时,可在 with 中放 BoxCxFn 或如示例中的 Metadata::from_fn(async |cx| ...)。真实用例见 examples/metadata/src/products/product_id.rs:它按路径参数查询商品,再生成标题、描述与 OpenGraph 图片,并借助 #[memoize] 让页面与元数据加载共享同一次查询结果。
页面即组件:body prop 的复用价值
#[page] 展开时会为函数加上 #[component],并生成一个同名常量标记。其结果是:页面可以在 view! 中被当作普通组件调用,用于预览、嵌入或组合。区别在于,带请求体参数的页面不再解析请求,而是把已解析的值通过名为 body 的 prop 传入:
#[page]
async fn preview(cx: &Cx) -> Result<impl View> {
let query = Search { q: String::from("topcoat") };
Ok(view! {
contact::contact(body: Form(query))
})
}
宏内部的处理逻辑是:把第二个参数的模式替换为 body,并在函数体开头补一句 let 原模式 = body;,从而在不改变页面正常调用语义的前提下支持组件调用。若原参数名本来就是 body,则不做改写。组件的通用规则(props、#<a href="https://link.gitcode.com/i/58965ed5137ae9fd4cc5ba5e936fb655" target="_blank">into]、child、递归组件需 boxed)见 [docs/view/component.md。
注册:三种方式与各自的边界
#<a href="https://link.gitcode.com/i/7d94ec029a237fadd23b1258eca261d1" target="_blank">page] 只负责“声明”,注册仍需显式完成。RouterBuilder::page 的定义非常轻量,仅把页面装箱入队([crates/topcoat-router/src/builder.rs):
pub fn page(mut self, page: impl Page) -> Self {
self.pages.push(Box::new(page));
self
}
对应的三种注册路径:
1. 模块路由(推荐默认)
// src/app.rs
use topcoat::router::{Router, module_router};
pub fn router() -> Router {
module_router!().build()
}
module_router!() 通过链接期发现(inventory)收集所有模块推导的 #[page],要求启用 discover feature(topcoat crate 默认开启)。它不扫描文件系统,因此每个路由模块必须经由 mod 声明被编译进程序。
2. 手工注册绝对路径处理器
use topcoat::{context::Cx, router::module_router, Result};
# use topcoat::{router::page, view::{View, view}};
#[page("/legacy")]
async fn legacy(cx: &Cx) -> Result<impl View> {
Ok(view! { <h1>"Legacy"</h1> })
}
pub fn router() -> topcoat::router::Router {
module_router!().page(legacy).build()
}
完全不使用模块路由时,则用 Router::builder().page(...),参考 examples/manual-router/src/main.rs,该示例逐一注册了 root_layout、docs_layout 与四个页面。
3. 一次性发现全部显式路径处理器
use topcoat::router::{Router, RouterBuilderDiscoverExt, module_router};
pub fn router() -> Router {
module_router!().discover().build()
}
discover() 会同时收编绝对路径的页面、布局、图层等;而需要在注册时传入具体值的东西(如 AssetBundle)仍需手工调用。
与布局协作:PageWithLayouts 的组装顺序
页面与布局的绑定完全基于路径前缀,而不依赖目录层级。核心选择逻辑是 layouts_for_path:
let mut matching: Vec<_> = layouts
.iter()
.filter(|(layout, _)| path.starts_with(layout.path()))
.collect();
matching.sort_by_key(|(layout, _)| layout.path().len());
由此得到三条可验证的行为:
- 只保留“路径前缀匹配”的布局,并按路径长度升序排列,即最不具体的在最外层;
- 相同路径的多个布局,注册顺序在前的位于外层(测试
for_path_keeps_the_earlier_of_a_shared_path_outside验证); - 前缀匹配是按段的:
/admin不会匹配/administrator(测试for_path_rejects_partial_segments)。
渲染时 PageWithLayoutsInner::render 从最内层向外逐层包裹:
let mut view = self.page.render(cx, body);
for layout in self.layouts.iter().rev() {
view = layout.render(cx, Slot::new(view));
}
view
于是 /settings/profile 的渲染顺序为 root_layout → settings_layout → profile。上下文的合并顺序恰好相反:PageWithLayouts::context 先安装各布局的值,再安装页面的值,从而让页面覆盖布局、内层布局覆盖外层布局。Slot 在实现上就是 Child<'a> 的类型别名。
值得注意的是,布局上下文在构建路由时只构建一次并被复用,因此不要在 with(...) 中放入依赖单次请求的可变状态。
链接与“当前页”:href! 与 is_current
绝对路径页面脱离模块树后,硬编码 URL 容易随重构失效。宏为每个页面生成 HrefTarget 实现,href!(page_fn) 会向当前请求所在的路由器反查该页面注册的实际路径;若页面未注册在当前路由器上,会 panic 并提示 page ... is not registered on the router serving this request。用法见 examples/manual-router/src/main.rs:
<a href=(href!(home))>"home"</a>
导航高亮则使用页面自身的 is_current(cx),它只比较 RouteId,因此 /posts/1 与 /posts/2 都会把同一个“文章”导航项标记为当前。注意其文档中标注的 panic 条件:请求未匹配任何路由(路径无端点,或端点没有对应方法的处理器)时调用会 panic。
实战:一个带参数、错误处理与元数据的页面
综合上面的机制,下面这个完整示例(改编自 examples/error/src/posts/post_id.rs 与 examples/metadata/src/products/product_id.rs)展示了典型的生产写法:
// src/app/posts/post_id.rs → GET /posts/{post_id}
use topcoat::{
Result,
context::Cx,
metadata::Metadata,
router::{error::RouterErrorExt, module_param, page},
view::{View, view},
};
// 路径参数:解析失败映射为 400;`not_found` 则映射为 404
module_param!(pub(crate) post_id: u64 else bad_request);
#[page(with(Metadata::from_fn(async |cx| {
let id = *post_id(cx)?;
Ok(Metadata::new().title(format!("Post {id}")))
})))]
pub(crate) async fn post(cx: &Cx) -> Result<impl View> {
let title = match *post_id(cx)? {
1 => Some("Hello Topcoat"),
2 => Some("Error handling"),
_ => None,
}
.ok_or_not_found()?; // 404 由布局中的 error_boundary 接管
Ok(view! { <h1>(title)</h1> })
}
这个例子串起了四条链路:module_param! 提供 {post_id} 段与读取函数、with(Metadata::from_fn(...)) 在页面渲染前向布局暴露元数据、else bad_request 把解析失败转成路由错误、ok_or_not_found() 让外层 error_boundary 渲染品牌化的 404 页面(详见 docs/router/error.md)。按模块路由的规则,该文件通常位于 src/app/posts/post_id.rs,并需要 src/app.rs、src/app/posts.rs 中的 mod 声明将其纳入编译。
常见错误与排查清单
| 现象 | 原因 | 处理 |
|---|---|---|
page functions must be async |
函数缺少 async |
改为 async fn |
page functions must declare a return type |
省略了 -> Result<impl View> |
显式声明返回类型 |
a relative path must start with ./ |
写了 "." |
用 "./" 表示模块路径加尾斜杠 |
a relative path cannot leave the module path |
写了 ".." 或 "../x" |
改用 / 开头的绝对路径并手工注册 |
| 页面 404,但函数确实存在 | 使用了绝对路径却未注册 | .page(fn) 或 .discover() |
| 同一路径构建路由时报冲突 | 同模块多个处理器共享派生路径且方法重叠 | 拆分模块、改用相对路径,或错开方法 |
href! 运行时 panic |
页面未注册在当前路由器上 | 检查注册方式与模块可见性 |
| 尾斜杠访问异常 | /users 与 /users/ 被视作不同路径 |
统一声明形式,必要时配置 trailing_slash |
小结
#<a href="https://link.gitcode.com/i/91de9f8771ac0da620fb0ce6f9182301" target="_blank">page] 的价值在于把“路由声明、请求解析、视图渲染、组件复用”压缩进一个函数签名里:路径可以来自模块树、相对扩展或绝对声明;方法默认 GET 且可通过单值、列表或 * 覆盖;第二个参数以 FromRequest 抽取请求体,并在组件调用时退化为 body prop;with(...) 让布局在页面运行前获得元数据;注册则交由 module_router!()、RouterBuilder::page 或 discover() 完成。把这些机制与 Page、ModulePage、PageWithLayouts 的源码对照阅读,可以在遇到路径冲突、链接失效或上下文被覆盖时快速定位根因。进一步阅读建议从 [docs/router/module.md、docs/router/layout.md 与 docs/router/route.md 入手,形成对页面、布局与 API 路由的整体认知。