Page Modes
Overview
A single page can be set up to handle more than one kind of user action, which we call “page modes”.
For example, a blog post page have a mode for editing the post, publishing the draft, etc.
+--------+ | | --> publishPost | blog | --> editPost | post | --> deletePost | | +--------+
How It Works
When a page loads, THT will look for a “mode” function to call as the entry point.
By default, it looks for main()
, but you can specify other functions, described below.
Main Mode
If your page has a main
function, it will automatically be called when the page is loaded with a HTTP GET request.
fun main { print('Hello World!') }
Post Mode
If the page is loaded as an HTTP POST request, it will call a postMode()
function if it is present.
This is most often used when a form is submitted.
// Default mode (HTTP GET) fun main { // Ex: print the form } // Runs when the form is submitted (HTTP POST) fun postMode { $data = Input.postAll({ name: 's' email: 'email' }) if $data.ok { // Ex: add it to the database } // Redirect return url'/form-thanks' }
Other Methods
THT will also respond to methods like DELETE, PUT, etc. with corresponding modes. (e.g. putMode)
This can be useful if you want to support a more strictly REST-based API.
However, it is often simpler to use POST with a clear route name. (e.g. /article/123/delete
)
Mode By Post Param
If there is a parameter named mode
in the Input data, THT will call the corresponding function, appended with “-Mode”.
This is a convenient way to support multiple actions via AJAX calls on the same page.
This takes precedence over the modes described above.
// Post data: // { mode: 'delete', articleId: 1234 } fun deleteMode { $articleId = Input.post('articleId', 'i') // Ex: update database // JSON response return { status: 'deleted' } }
Route Params
This also works for params defined in a route:
// Route: /article/{articleId}/{mode}: article.tht // URL: /article/1234/delete fun deleteMode { $articleId = Input.route('articleId', 'i') // Ex: update database // JSON response return { status: 'deleted' } }
Return Values
If your mode function returns a value, THT will use that value as the response to the browser.
Return Value | Response |
---|---|
html TypeString |
HTML |
Page object | Full HTML document |
Map {...} |
JSON payload |
url TypeString |
Redirect to the URL |
true |
Refresh the current page |
Example:
fun main { // Redirect return url'/another/page' }