Dynamic Navigation (Example)
Overview
We assume you already created a new app to work in.
This tutorial will cover:
- Dynamic routing
- Templates
Step 1: Add the Route
For this example, instead of relying on the automatic page URL, we want to include a dynamic color
name in the URL.
Edit app/settings/app.jcon
and modify the routes
block so that it looks like this:
routes: { /colors/{color}: colors.tht }
Step 2: Create the Page
Create a new file: pages/colors.tht
.
Copy and paste the following code:
// THT will automatically call main() when the page loads. function main() { // Get the current color from the URL $pageColor = Input.route('color'); print('color: ' ~ $pageColor); }
Load the page to make sure it works:
http://localhost:8888/colors/red
You will see something like this:
(Try changing the color in the URL.)
Step 3: Add a Template
Now let’s send the page back as HTML, using a template.
First, we replace the print
line with a call to Response.sendPage
, which sends a complete HTML document.
In the css
field, we tell it to use THT's built-in Base Stylesheet.
Replace the content of colors.tht
with this code:
function main() { $pageColor = Input.route('color'); Response.sendPage({ body: pageHtml($pageColor), css: Css.plugin('base'), }); } template pageHtml($color) { <main style="border-top: solid 2rem {{ $color }}"> <h1>{{ $color.toUpperCaseFirst() }}</> </> }
This is what you should see when you refresh the page:
Step 4: Add Navigation Links
Create a new function that returns a list of colors.
By keeping this list separate from the template, it will be easier to change later on.
function getLinkColors() { return ['red', 'aqua', 'orange']; }
Then update the page template to include a new template that creates a link to each color.
The --
(double-dash) symbol is used to embed lines of THT code. (Think “code line”.)
template pageHtml($color) { <main style="border-top: solid 2rem {{ $color }}"> <h1>{{ $color.toUpperCaseFirst() }}</> {{ linksHtml() }} </> } template linksHtml() { -- foreach getLinkColors() as $linkColor { <a href="/colors/{{ $linkColor }}"> {{ $linkColor.toUpperCaseFirst() }} </> -- } }
This is what you should see when you refresh the page:
Step 5: Experiment
Try changing and expanding the code to see what happens.
Ideas:
- Add new colors, like
turquoise
andgray
. - Modify
/pages/css.tht
and remove the call toCss.plugin
. See what the page looks like without it. - If the route has a color that is not in the list of links, call
Response.sendError(404)
.