Routing in LWR
LWR provides a great deal of routing sophistication. Here we start with a basic routing example and an overview of the properties you can use for a route.
Let’s add a page to our site and do some basic (and fast!) routing.
- Now that you’ve got your
StaticSiteproject, make a copy of the
about.mdfile. Keep the new file in the
contentdirectory and name the file explore.md.
- Edit the
explore.mdfile. You can change the first line from
# About LWRto
# Explore LWR. Save the file.
- Open the
main_layout.njkfile. On a new line, add
<li><a href="/explore">Explore</a>under the
aboutline. Save the file.
- Finally, open the
lwr.config.jsonfile. Copy the entire block of code for
about, including the curly brackets, and paste it below the
explorethroughout, and don’t forget to add the comma after the closing bracket in the
aboutblock. Save the file.
- If you're still in the
StaticSitedirectory from when you first made your site, just type
npm run startin the terminal to see your changes. Your updated
StaticSiteproject should run at http://localhost:3000/, with a new Explore LWR page and a working Explore button.
What just happened is that you:
- created a Markdown page (
explore.md) and gave it new heading text ("Explore LWR")
- updated the site navigation in the Nunjucks layout (
main_layout.njk) file to include a new Explore button
- updated the JSON routing configuration file (
lwr.config.json) to let LWR know how to route to the new page
- you gave an
idfor the page (
- you provided the
pathfor the page (
- you provided a
contentTemplatefor the page (
- you told LWR which
layoutTemplateyou wanted to use for the page (
main_layout.njk, the same as for your other pages in this example, though that’s not required)
- you gave an
A Deeper Dive into LWR Routing
Each server-side route includes some of these properties:
id: The unique identifier for the route.
path: The unique URI path from which the route is served.
layoutTemplate: The path to a static template that renders the page layout.
contentTemplate: The path to a static template that renders the page content.
rootComponent: The top-level Lightning web component that LWR bootstraps into the HTML output for the route. Each route must have either a
contentTemplate, but not both. (If you do use a
rootComponent, LWR applies a default
contentTemplateto render it.)
properties: A JSON object that can be passed to the templates as context.
routeHandler: A path to a route handler. Route handlers are an advanced topic, but for now know that you can customize the page response using a route handler. A route handler is a function that is configured for a route.
cache: The cache settings for the routing, including:
Here’s an example of the routes in a more complex
lwr.config.json file that includes a couple more properties:
Now that we've examined how LWR handles templates and routing, let's work with LWR's compile-time data in more complex scenarios.