- Docs
- Sites
Routing
A Lithe site is one page, so routing works like in any single-page app: the component that holds the routes follows the path of the URL and shows the matching content. Want one page per route, rendered at build time? That's a Kobweb site, which owns the routes and mounts Lithe components in its pages.
<script kotlin>
import io.github.ayfri.lithe.matchRoute
import web.window.window
var path by window.route()
</script>
<a href="/">Home</a> <a href="/blog/hello">Post</a>
@if (val post = matchRoute("/blog/:slug", path)) {
<h1>Post {post["slug"]}</h1>
} @else if (matchRoute("/", path) != null) {
<h1>Home</h1>
} @else {
<h1>Not found</h1>
}
The path
var path by window.route() is the path of the page, like a page value. Writing it moves to that path. Static rendering takes it as / and the browser gives the real one once the page is hydrated, so a component that reads it needs the browser.
Matching
matchRoute(pattern, path) gives the values of the :name segments of a pattern, or null when the path isn't one of its URLs.
- A
*as the last segment takes the rest as*. - Trailing slashes count for nothing.
- A captured value is decoded.
Moving
navigate(to, replace, state)moves to a path from a handler.stateis kept with the entry of the history and copied by the browser withstructuredClone: aString, aBoolean, anIntor aDoublecome back as they were, and a Kotlin class, list or function doesn't, since the copy keeps the fields and not the type.navigationState<Int>()reads it back.- Links need no code: the Navigation API turns every same-origin link, back and forward into a move that keeps the page loaded. A link to a file (a name with an extension), a download, a form, a reload and a move to a hash are left to the browser.
- Where the browser lacks the API, a link loads its page as usual, which the host has to answer with the page of the app for every route. The dev server does it for a path without extension that a browser asks as a page.
A router of your own
A router package is plugged in as a RouteSource: path() reads where the page is, listen(change) calls change after each move and gives back what stops it, and go(to, replace) moves. window.route(source) follows it like it follows the browser.