URL Router
Automatic Page URLs
The easiest way to add a web page is to create a .tht
file in the code/pages
directory.
The file name is always dash-case.
Each page will automatically get a matching URL.
For example:
File | URL |
---|---|
code/pages/hello.tht | /hello |
code/pages/hello-world.tht | /hello-world |
code/pages/misc/my-other-page.tht | /misc/my-other-page |
Home Route
By default, the root URL routes to pages/home.tht
.
File | URL |
---|---|
code/pages/home.tht | https://yoursite.com |
Custom Routes
You can define dynamic routes in config/app.jcon
.
Each URL pattern points to a file in the pages
directory.
Dynamic parameters can be added via curly braces, e.g. {myParam}
.
For example:
routes: { /user/{userName}: user.tht /blog/{articleId}/{slug}: blog.tht /forum/post/{postId}: posts/view-post.tht /forum/post/{postId}/edit: posts/edit-post.tht }
The parameter must take up an entire sub-path between slashes. For example:
// ✕ BAD /profile/user{userId} // ✓ OK /profile/{userId}
Route Params
You can access the value of a route param with Input.route.
// Route: // /blog/{articleId}/{slug} // URL: // /blog/1234/my-favorite-things // i = integer Input.route('articleId', 'i') //= 1234 Input.route('slug').humanize() //= 'My Favorite Things'
Scrambled IDs
You can hide the true value of your numeric ID's using the String.scrambleId method.
// app.jcon: routes: { /profile/{userId}: user.tht } // In your app... // Create scrambled ID $scrambledUserId = String.scrambleId(123) url'/profile/{}'.fill($scrambledUserId) // Get unscrambled ID $userId = Input.getRoute('userId', 'unscramble')
Redirect Routes
You can set up a redirect from one URL to the other.
routes: { /some-url: /another/url }
Default Route
If a route does not exist, THT will look for a default.tht
file in your pages
directory.
You can use this to implement a custom 404 page, or your own fallback routing logic.
Otherwise, THT will return a “404 Not Found” error.
// pages/default.tht //---------------------------- fun main { // URL: /blog/post-123 $parts = Request.getUrl().pathParts() //= ['blog', 'post-123'] if $parts[1] == 'blog' { ... } }
Valid Routes
There are the only the characters allowed in a URL:
a-z0-9_-./
THT will automatically respond with a 404 error page if any other character is present in the URL.
NOTE: Trailing slashes (directory paths) are NOT allowed.
✕ Bad | ✓ OK |
---|---|
/forum/posts/ | /forum/posts |
/article/123/My-Favorite-Recipe | /article/123/my-favorite-recipe |
HTTP Methods
To handle different HTTP methods, see Page Modes.