路由参数
路径中大括号内的部分是路由参数。它的值会以同名变量的形式传给控制器,因此{id}会变成$id:
<!-- routes.kscript -->
<KScript.Routes>
<import path="controllers/people.kscript" as="people" />
<Get path="/people/{id}" to="people.page" />
<Get path="/archive/{year?}" to="people.index" />
<Get path="/files/{path*}" to="people.index" />
</KScript.Routes>// routes.kscript
import KScript.Http
import "controllers/people.kscript" as people
Routes {
Get(path: /people/{id}, to: @people.page)
Get(path: /archive/{year?}, to: @people.index)
Get(path: /files/{path*}, to: @people.index)
}{year?}是可选的,{path*}则接收路径的其余部分。路径是斜杠路径,因此无需加引号:path: /people/{id}和path: "/people/{id}"是相同的。无论哪种方式,{id}都是路由参数,绝不会从变量中填充。
参数规则
where: 为参数设置一条规则。不符合该规则的请求不会匹配此路由,因此会继续尝试下一个路由:
<!-- routes.kscript -->
<KScript.Routes>
<import path="controllers/people.kscript" as="people" />
<Get path="/people/{id}" to="people.page" where="{ id: int }" />
<Get path="/posts/{slug}" to="people.index" where="{ slug: slug }" />
</KScript.Routes>// routes.kscript
import KScript.Http
import "controllers/people.kscript" as people
Routes {
Get(path: /people/{id}, to: @people.page, where: { id: int })
Get(path: /posts/{slug}, to: @people.index, where: { slug: slug })
}规则为 number、int、alpha、alnum、slug、uuid,或用引号括起来的正则表达式。在 XML 中,同样的规则写作 where="id: int, slug: slug"。