Version: v0.7.1 - Beta.  We welcome contributors & feedback.

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 user profile page might provide a mode for saving contact info, and another mode for sending a private message, etc.

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.

fn 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)
fn main {

    // e.g. print the form
}

// Runs when the form is submitted (HTTP POST)
fn postMode {

    $data = Input.postAll({
        name: 's',
        email: 'email',
    })

    if $data.ok {
        // e.g. 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 }

fn deleteMode {

    $articleId = Input.post('articleId', 'i')

    // e.g. 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

fn deleteMode {

    $articleId = Input.route('articleId', 'i')

    // e.g. 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:

fn main {

    // Redirect
    return url'/another/page'
}