Topcoat `[layout]` 布局宏完全指南:模块路由、嵌套顺序、路由上下文与组件化复用
Topcoat #[layout] 布局宏完全指南:模块路由、嵌套顺序、路由上下文与组件化复用
#<a href="https://link.gitcode.com/i/7b18ff299c02b1131ad333c5e45debd1" target="_blank">layout] 是 Topcoat 路由体系中最能体现“布局即组合”思想的一环:它把一个 async fn 变成可包裹多个页面的布局处理器,既能在模块路由中根据模块树自动推导 URL 前缀,也能用绝对路径独立注册,甚至可以直接当作组件在任意视图中复用。本文以 [crates/topcoat-router/macro/docs/layout.md 为主体骨架,结合宏语法解析、trait 定义、嵌套选择算法与测试用例,把这条文档里的每一处约定都落到可运行的细节上。
一、#[layout] 解决什么问题
在 Topcoat 里,页面(#[page])负责产出内容,布局负责提供外层骨架:<html> 文档结构、导航栏、侧边栏、页脚、全局 <head> 元数据等。#[layout] 声明的是“一个能包住内部页面的处理器”,它在注册后由路由器按路径前缀自动匹配,前缀命中的页面都会被它包裹。
这个宏定义在 crates/topcoat-router/macro/src/lib.rs,文档通过 include_str! 直接嵌入 docs/layout.md,因此文档内容与实现是同一份源码事实。
#[doc = include_str!("../docs/layout.md")]
#[proc_macro_attribute]
pub fn layout(attr: TokenStream, item: TokenStream) -> TokenStream {
match topcoat_router_grammar::layout::Layout::parse(attr.into(), item.into()) {
Ok(value) => quote! { #value }.into(),
Err(error) => error.to_compile_error().into(),
}
}
二、三种路径写法:模块派生、模块下相对、绝对独立
#<a href="https://link.gitcode.com/i/9b010440d4e2aa39c840a1f36dc56b26" target="_blank">layout] 的属性参数由 [LayoutAttr 解析,结构上就是“一个可选路径 + 若干 with(...)”:
pub struct LayoutAttr {
pub path: Option<HandlerPath>,
/// The comma between the path and the `with(...)` entries.
pub comma: Option<Token![,]>,
pub context: Punctuated<RouteContext, Token![,]>,
}
三种写法对应三种注册语义:
| 写法 | 生成的 trait 实现 | URL 前缀来源 | 注册方式 |
|---|---|---|---|
#[layout] |
ModuleLayout |
所在模块的模块路径 | module_router!() 自动发现 |
#[layout("./admin")] |
ModuleLayout |
模块路径 + ./ 后面的相对路径 |
module_router!() 自动发现 |
#[layout("/settings")] |
Layout |
绝对路径,与模块树无关 | RouterBuilder::layout(...) 或 .discover() |
2.1 无路径:交给模块路由推导
use topcoat::{Result, context::Cx, router::{Slot, layout}, view::{View, view}};
#[layout]
async fn settings_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
Ok(view! {
<section>
<nav>"Settings nav"</nav>
(slot)
</section>
})
}
把这段代码放在 src/app/settings.rs 且该模块处于 module_router!() 的根模块之下,它就会包裹 /settings 及其所有子页面。模块如何映射为 URL 段的规则(静态名转 kebab-case、_ 前缀模块作为分组不进入 URL)在 crates/topcoat-router/docs/module.md 中有完整表格,此处只需记住:布局的 URL 前缀与同模块的页面完全一致。
2.2 ./ 前缀:在模块路径下延伸
#[layout("./admin")]
async fn admin_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
Ok(view! {
<section>
<nav>"Admin nav"</nav>
(slot)
</section>
})
}
同样位于 src/app/settings.rs,它只包裹 /settings/admin 及其子页面。相对路径的处理逻辑在 HandlerPath:./ 前缀被识别为相对路径,去掉前导的 . 后剩余部分(如 /admin)在构造 ModuleLayout::relative_path() 时返回,由模块路由器拼接:
pub fn relative_path_method(&self) -> Option<TokenStream> {
let path = self.relative()?;
Some(quote! {
fn relative_path(&self) -> ::core::option::Option<&#topcoat_router::Path> {
const PATH: &#topcoat_router::Path = #topcoat_router::Path::new(#path);
::core::option::Option::Some(PATH)
}
})
}
两个容易踩坑的边界由语法层直接拒绝:单独的 "." 会报 a relative path must start with ./;任何 .. 开头(如 "../sibling")会报 a relative path cannot leave the module path; use an absolute path starting with / instead。也就是说,布局不能用相对路径“向上越层”,想跨模块共享外壳请改用绝对路径。
2.3 绝对路径:与模块树解耦,但必须手动注册
use topcoat::{Result, context::Cx, router::{Slot, href, layout}, view::{View, view}};
#[page("/")]
async fn home(cx: &Cx) -> Result<impl View> { Ok(view! { "Home" }) }
#[layout("/")]
async fn root_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
Ok(view! {
<!DOCTYPE html>
<html>
<body>
<nav><a href=(href!(home))>"Home"</a></nav>
(slot)
</body>
</html>
})
}
关键点在于:module_router!() 只发现模块派生的处理器,绝对路径布局会被它忽略。必须显式传入函数名:
Router::builder()
.layout(root_layout)
.page(home)
.build()
或者开启 discover 特性后统一收集(module_router!().discover() 内部会调用 discover_layouts)。绝对路径布局在 crates/topcoat-router/grammar/src/layout.rs 中走另一分支,生成 Layout 而非 ModuleLayout:
impl #topcoat_router::Layout for #ident {
fn path(&self) -> &#topcoat_router::Path {
const PATH: &#topcoat_router::Path = #topcoat_router::Path::new(#path);
PATH
}
// context() / render() ...
}
注意宏还会额外生成一个与函数同名的常量标记(const root_layout: root_layout = ...),这样 .layout(root_layout) 中传入的是可被 impl Layout 接受的值,而不是裸函数名:
#[#topcoat_view_macro::component]
#item
#(#docs)*
#[doc(hidden)]
#[allow(non_upper_case_globals)]
#vis const #ident: #ident = #ident { __marker: ::core::marker::PhantomData };
这也是为什么布局在被 #[layout] 标注后依然可以在视图中当组件调用——它首先是一个 #[component]。
三、处理器签名:由宏强制校验的三条硬约束
文档明确要求:函数必须是 async,第一个参数是 cx: &Cx(即使不用也要写),第二个参数是 slot: Slot<'_>,不接受任何其他参数,并且必须有返回值类型,返回 Result<...> 包裹的 View。
这些不是约定俗成,而是编译期错误。校验实现在 LayoutItem:
if item.sig.asyncness.is_none() {
return Err(syn::Error::new(item.sig.fn_token.span(), "layout functions must be async"));
}
if let ReturnType::Default = &item.sig.output {
return Err(syn::Error::new(item.sig.fn_token.span(), "layout functions must declare a return type"));
}
item.sig.cx_param()?;
let mut params = item.sig.params();
let slot = params.next();
if !slot.is_some_and(|slot| matches!(&*slot.pat, Pat::Ident(pat) if pat.ident == "slot")) {
return Err(syn::Error::new_spanned(
&item.sig,
"layout functions must take a `slot: Slot<'_>` parameter after `cx`",
));
}
if let Some(extra) = params.next() {
return Err(syn::Error::new_spanned(
extra,
"layout functions only take `cx: &Cx` and `slot: Slot<'_>`",
));
}
对应的单元测试在同一个文件底部,可直接作为错误信息参照:
| 错误写法 | 编译错误摘要 |
|---|---|
fn shell(cx: &Cx, slot: Slot<'_>) -> ... |
layout functions must be async |
async fn shell(cx: &Cx, slot: Slot<'_>) {} |
layout functions must declare a return type |
async fn shell(slot, cx) -> ... |
提示需要 cx: &Cx |
async fn shell(cx: &Cx) -> ... |
must take a `slot: Slot<'_>` parameter |
追加 body: Form<A> 等参数 |
layout functions only take ... |
为什么布局不能像 #[route] 那样接收 Body 或表单?因为布局的定位是“渲染外壳”,它不参与请求体解析;需要请求级处理(鉴权、日志、改响应头)应使用 #[layer]。这也是 Topcoat 中 layout(包页面)与 layer(包请求)职责分离的体现。
Slot 到底是什么
在 crates/topcoat-router/src/page.rs 中它只是一个类型别名:
/// The content a [`Layout`] wraps: the page, already composed with any inner
/// layouts.
pub type Slot<'a> = Child<'a>;
而 Child<'a> 定义在 crates/topcoat-view/src/child.rs,本质是组件子内容的容器,Slot::new(view) 可以把任意 View 包装成子内容。因此布局内 (slot) 的插值位置,就是“页面 + 所有更内层布局”最终渲染的位置。
四、Layout 与 ModuleLayout 两个 trait
模块派生与绝对路径的布局分别实现两个 trait,二者签名几乎一致,区别只在“前缀如何取得”。绝对路径版 Layout:
pub trait Layout: Send + Sync + 'static {
fn path(&self) -> &Path;
fn context(&self) -> ContextMap { ContextMap::new() }
fn render<'a>(&'a self, cx: &'a Cx, slot: Slot<'a>) -> BoxView<'a>;
}
模块版 ModuleLayout 用 module_path() 与可选的 relative_path() 取代 path(),由 ModuleRouterBuilder 在注册时算出真实路径并包装为 ResolvedLayout(实现 Layout):
pub fn layout(mut self, layout: impl ModuleLayout) -> Self {
let path = self.resolve_path(layout.module_path(), layout.relative_path());
self.inner = self.inner.layout(ResolvedLayout::new(layout, path));
self
}
resolve_path 的行为在 crates/topcoat-router/src/module/router.rs 中有详细注释与测试覆盖:无相对路径时直接用模块路径;Some(relative) 时拼接;Path::ROOT(即 ./)会在模块路径后补一个尾斜杠,使 /settings 变成 /settings/;而在根模块上使用 ./ 会 panic,因为根路径没有“尾斜杠形式”。
宏生成的 render 方法则负责把 slot 注入组件的 slot 属性:
fn render<'a>(&'a self, cx: &'a #topcoat_context::Cx, slot: #topcoat_router::Slot<'a>) -> #topcoat_view::BoxView<'a> {
let props = <#ident as #topcoat_view::Component>::props_builder()
.slot(slot)
.build();
::std::boxed::Box::pin(#topcoat_view::HoistView::new(
#topcoat_view::internal::ThenView::new(
<#ident as #topcoat_view::Component>::render(#ident, cx, props)
)
))
}
换句话说,布局在运行时就是“带一个必填 slot 属性的组件”,这与文档“Layouts as components”一节的说法完全对应,不是两套机制,而是同一套机制的两种使用入口。
五、嵌套顺序:路径最短者最外层
这是 #[layout] 最容易出错的地方。文档给出的规则是:多个布局命中同一页面时,从**最不具体(最外层)到最具体(最内层)**嵌套。
选择与排序逻辑在 layouts_for_path:
pub(crate) fn layouts_for_path<'a>(
layouts: &'a [(Arc<dyn Layout>, ContextMap)],
path: &Path,
) -> Vec<&'a (Arc<dyn Layout>, ContextMap)> {
let mut matching: Vec<_> = layouts
.iter()
.filter(|(layout, _)| path.starts_with(layout.path()))
.collect();
matching.sort_by_key(|(layout, _)| layout.path().len());
matching
}
渲染时从最内层向外反向套壳,见 PageWithLayoutsInner::render:
fn render<'a>(&'a self, cx: &'a Cx, body: Body) -> BoxView<'a> {
let mut view = self.page.render(cx, body);
for layout in self.layouts.iter().rev() {
view = layout.render(cx, Slot::new(view));
}
view
}
由此可以得出几条实用结论:
- 顺序与注册顺序无关。
RouterBuilder::page的文档明确写着 “Order doesn't matter: layout matching is based on path prefixes, not registration order.” - 前缀匹配按路径段边界。测试
for_path_rejects_partial_segments验证了/admin布局不会命中/administrator。 - 同路径多个布局:手工注册时,
layouts中靠前者在外层(测试for_path_keeps_the_earlier_of_a_shared_path_outside);但发现机制下同路径会直接 panic,见builder.rs与module/router.rs:
assert!(
seen.insert(layout.path().to_owned()),
"multiple discovered layouts registered for the same path \"{}\"",
layout.path()
);
原因文档也说得很直白:链接期发现不保证顺序,同路径两个布局谁在外层是未定义的。需要叠加多层同路径外壳,应合并到一个布局组件里,或改用显式 .layer()/.layout() 注册来获得确定顺序。
文档示例的完整验证
#[layout]
async fn root_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
Ok(view! { <html><body>(slot)</body></html> })
}
mod settings {
use super::*;
#[layout]
async fn settings_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
Ok(view! {
<div class="settings-shell">
<nav>"Settings nav"</nav>
(slot)
</div>
})
}
mod profile {
use super::*;
#[page]
async fn profile(cx: &Cx) -> Result<impl View> {
Ok(view! { <h1>"Profile"</h1> })
}
}
}
请求 /settings/profile 的渲染链是 root_layout > settings_layout > profile。<html><body> 来自根布局,.settings-shell 包裹它内部的内容。集成测试 crates/topcoat-router/macro/tests/layout.rs 用一段等价的绝对路径版本做了断言:
let router = Router::builder()
.layout(shell) // #[layout("/")]
.layout(section_layout) // #[layout("/nested")]
.page(inner) // #[page("/nested/inner")]
.build();
let (status, body) = send(&router, "/nested/inner").await;
assert_eq!(status, 200);
assert_eq!(body, "<main><section data-path=\"/nested/inner\">inner</section></main>");
输出顺序清楚表明:/ 前缀的 shell 在最外,/nested 的 section_layout 在其内,页面在最里。
六、路由上下文:with(...) 为布局挂载默认值
#[layout] 可以携带任意多个 with(...),例如:
#[layout(with(Title("My shop")))]
async fn shop_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> { /* ... */ }
#[layout("/", with(Title("My shop")))]
async fn root_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> { /* ... */ }
多个 with(...) 之间用逗号分隔。每个条目的括号内容被原样保留为表达式,由 RouteContext::context_method 生成 context() 方法:
fn context(&self) -> #topcoat_context::ContextMap {
let mut __topcoat_context = #topcoat_context::ContextMap::new();
__topcoat_context.insert(Title("My shop"));
__topcoat_context
}
关键语义有三种,都值得记住:
- 同类型后写覆盖先写:
insert按顺序执行,后一个同类型值遮蔽前一个。 - 内层可遮蔽外层:布局与页面的上下文在
PageWithLayouts::context中按“外层布局 → 内层布局 → 页面”的顺序合并,后者覆盖前者:
fn context(&self) -> ContextMap {
let mut context = ContextMap::new();
for layout in &self.inner.layouts {
layout.context().install(&mut context);
}
self.inner.page.context().install(&mut context);
context
}
- 读取方式是类型驱动的:请求期用
context::<T>(cx)取引用,或用try_context::<T>(cx)取Option<&T>(见crates/topcoat-core/src/context/lookup.rs)。抽象层叠加时不必关心值来自哪一层。
测试 layout.rs 直接验证了这两种声明形式都能取回值:
#[layout("/admin", with(Title("admin")))]
async fn admin(cx: &Cx, slot: Slot<'_>) -> Result<impl View> { /* ... */ }
#[layout(with(Title("module")))]
async fn module_admin(cx: &Cx, slot: Slot<'_>) -> Result<impl View> { /* ... */ }
let context = Layout::context(&admin);
assert_eq!(context.get::<Title>(), Some(&Title("admin")));
let context = ModuleLayout::context(&module_admin);
assert_eq!(context.get::<Title>(), Some(&Title("module")));
注意这两个断言来自不同的 trait:绝对路径布局用 Layout::context,无路径布局用 ModuleLayout::context。这也是判断一个布局“属于哪个世界”的最直接方式。
实战:用 with(...) 驱动侧边栏与标题
demos/admin 展示了工业级用法。根布局注入默认元数据(demos/admin/src/app.rs):
#[layout(
with(Metadata::new()
.title("Backroom")
.robots(Robots::new().index(false).follow(false)))
)]
async fn root(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
// <html> ... (slot) ... </html>
}
内层 _admin 分区的 shell 再注入一个“根据路由上下文动态计算标题”的 Metadata::from_fn,它会读取页面声明的 Crumb 或 Section(demos/admin/src/app/_admin.rs);而具体页面只需要一行:
#[layout(with(Section::Products))]
async fn section(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
Ok(view! { (slot) })
}
(见 demos/admin/src/app/_admin/products.rs。)
这种“空壳布局只用来声明上下文”的模式非常实用:它不改变 HTML 结构,只负责把 Section::Products 注入该分区的上下文,让外层 shell 渲染出正确的面包屑与高亮项。注意此类布局与同模块派生布局的路径不同(一个是 ./products 派生、一个在模块本身),因此不会触发“同路径重复发现”的 panic。
七、布局作为组件:slot 属性复用同一份外壳
文档最后一节指出:布局同时就是组件,Slot 就是它的 slot 属性。测试 renders_a_layout_as_a_component 给出了最小例:
#[page("/composed")]
async fn composed(cx: &Cx) -> Result<impl View> {
let content = view! { <p>"content"</p> };
Ok(view! { shell(slot: Slot::new(content)) })
}
请求 /composed 得到 <main><p>content</p></main>。这个能力有三个直接收益:
- 不需要为一次性页面注册布局:例如登录页、邮件预览页、错误页,可以直接把外壳当函数调用。
- 可以在布局中嵌套布局:一个布局的
slot里再放other_layout(slot: ...),形成显式的组合关系,而不依赖路径匹配。 - 测试友好:单元测试可以只渲染布局本身,不必构造完整
Router。
八、错误处理:error_boundary 保护 slot
文档要求“把 slot 放在 error_boundary 里以在内层渲染失败时展示自定义视图”,这在大型应用中非常重要:布局往往包住整页内容,一旦某个子组件 ? 抛错,整个响应会失败;而边界允许降级。
error_boundary 定义于 crates/topcoat/src/view/error_boundary.rs,签名要点是 fallback: FnOnce(Error) -> Result<V> 加一个默认的 child: Child<'_>:
#[component]
pub async fn error_boundary<V, F>(cx: &Cx, fallback: F, #[default] child: Child<'_>) -> Result<impl View>
where
V: View,
F: FnOnce(Error) -> Result<V> + Send,
放进布局时的写法:
use topcoat::{Error, Result, context::Cx, router::Slot, view::{View, error_boundary, view}};
#[layout]
async fn root_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
Ok(view! {
<html>
<body>
<nav>"My shop"</nav>
error_boundary(
fallback: |error: Error| Ok(view! {
<main class="error">
<h1>"Something went wrong"</h1>
<p>(error.to_string())</p>
</main>
}),
(slot)
)
</body>
</html>
})
}
需要留意的行为细节(来自该文件文档注释):一旦子内容失败,回退视图会替换边界内的全部内容,包括已经流式发送给浏览器的部分;页面其他区域不受影响。若 fallback 返回 Err,错误会继续向上传播到外层处理器,而处理器只能在响应开始流式输出之前修改状态码。
九、与页面、路由、层的协作边界
- 只包页面,不包
#<a href="https://link.gitcode.com/i/f02ea13c6f923e30c970b848f5e1ff09" target="_blank">route]:PageWithLayouts是围绕Page构造的([crates/topcoat-router/src/page.rs),#<a href="https://link.gitcode.com/i/0c721109cc4db6c3c8543f2b1b87c7df" target="_blank">route]注册的是独立Route。示例 [examples/manual-router/src/main.rs的注释也明确写着 routes “skip the layouts”,因此/api/health返回纯文本时不会套上<html>。 - 与
#<a href="https://link.gitcode.com/i/96e1a747237bd4d8ea19ba2ae2e52928" target="_blank">layer]的顺序不同:布局只影响视图渲染;层包裹的是整个请求与响应,且同路径多层时“后注册者在外层”(见 [crates/topcoat-router/src/builder.rs)。选择用哪个,取决于你要改的是 HTML 结构还是请求/响应本身。 - 分组模块中的布局仍然生效:
_marketing这类以_开头的模块不贡献 URL 段,但布局/层仍按逻辑模块路径匹配后代(见crates/topcoat-router/docs/module.md的 Groups 一节与测试group_modules_are_left_out_of_the_url)。示例examples/module-router/src/app/_marketing.rs正是用这个特性给一组顶级 URL 套统一外壳。 - 必须被编译才会被发现:
module_router!不做文件系统扫描,每个模块都要通过mod声明接入编译图,否则其中的#[layout]不会进入链接期收集。
十、注册方式速查与排错清单
// 1) 纯模块路由:无路径布局与 ./ 相对布局自动生效
pub fn router() -> Router {
module_router!().build()
}
// 2) 同时收编绝对路径布局/页面
pub fn router() -> Router {
module_router!().discover().build()
}
// 3) 完全手工注册(示例见 examples/manual-router)
pub fn router() -> Router {
Router::builder()
.layout(root_layout)
.layout(docs_layout)
.page(home)
.page(docs)
.build()
}
排错时按以下顺序定位:
| 现象 | 最可能的原因 | 依据 |
|---|---|---|
| 布局完全不生效 | 用了绝对路径却只调用 module_router!() |
模块路由器只发现 ModuleLayout |
无路径布局传给 Router::builder().layout(...) 编译失败 |
无路径生成的是 ModuleLayout,不是 Layout |
layout.rs #L161-L180 |
启动/构建时 panic:multiple discovered layouts registered for the same path |
同路径声明了两个可发现布局 | builder.rs #L143-L154 |
| 布局包裹了不该包裹的页面 | 前缀太长(如 /)或布局放在根模块 |
layouts_for_path 使用前缀匹配 |
| 期望的外层布局跑到了内层 | 误以为按注册顺序嵌套 | 排序依据是路径长度,非注册顺序 |
编译报 layout functions must be async / must take a slot |
签名不符合三条硬约束 | layout.rs #L52-L87 |
with(...) 的值读不到 |
读取类型与插入类型不一致,或被内层同类型覆盖 | ContextMap 按类型索引 |
结语
#<a href="https://link.gitcode.com/i/2c2966ddcbd9308b699874696f5eb0af" target="_blank">layout] 的价值不只是“少写几个 <html> 标签”,而是把“URL 结构、渲染外壳、路由上下文”三件事统一到同一个 async fn 上:模块树决定前缀,路径前缀决定嵌套,slot 决定内容插入点,with(...) 决定上下文默认值,而同一个函数在需要时又能退化为普通组件。理解 [Layout/ModuleLayout、layouts_for_path 与 context() 合并顺序 这三个实现锚点后,嵌套层级、注册方式与上下文遮蔽的所有行为都可以被推导而非试错。更多相邻主题可继续阅读 路由上下文、错误处理指南、组件与 slot 以及 模块路由完整规则。