Javascript Templates (JST)

Javascript Templates (JST) enable the easy creation of dynamic web pages and applications. Javascript Templates are HTML web pages that execute Embedded Javascript on the server before rendering the page back to the client. JST is an extensible environment and allows the direct binding of C functions to Javascript functions, so that a JST web page can easily access device or system data.

JST Handler

A JST document has a .jst extension and is processed by the jst handler. The JST handler executes JST scripts and replaces them with the corresponding script results. The user sees a normal HTML page, but it is one that was dynamically created by the JST handler.

JST Delimiters

To create a JST script field in a JST document, use the <% and %> delimiters. For example, the following JavaScript will output "Hello World" in place of the JST-delimited field:

Today is <% write("Hello" + " World"); %>

Scripting Execution

When a user's browser requests a JST document, the JST handler is invoked to serve the request. The JST document is read from the file system in a one-pass operation. Text in the document before JST delimiters is copied directly to the client. If JST delimiters are found, the script between the delimiters is executed and the resulting text is written to the client. The process continues until the end of the document.

Standard Functions

JST defines one standard function: write. This function writes data back to the client in the place of the JST script.

Defining JST functions

New JST functions can be created via websDefineJst. This binds a C function to a Javascript function. For example:

static getDate(int jid, Webs *wp, int argc, char **argv) {
    char *date = websGetDate(0);
    websWrite(wp, "%s", date);
    gfree(date);
}
websDefineJst("date", getDate);

Once defined, JST pages can use the new date function:

Today's date is: <% date(); %>

© Embedthis Software. All rights reserved.