Writing Templates

Templates are the workhorses of most Cadre applications. They are bundles of code that define how entries are viewed. They are equivalent to classes in standard object-oriented programming, as contrasted with entries, which are comparable to objects. (For clarity's sake, the overall look and feel of a Cadre site containing its header, navigation, and footer is usually called a layout.)


A template consists primarily of a set of modes, which are scripts bounded by [begin mode x] and [end mode x], where x is the name of the mode itself. Unlike normal scripts, however, key variables like $_body and @_this are replaced with those values from the entry using the template, not the template itself—just like in standard object-oriented programming.

In addition to the modes within a template, templates also experience inheritance. By setting the parent attribute of one template to another, the child template will override the parent's modes. For example, the standard news post template provides the info mode from the default template (example), although it overrides the edit mode. At present there is no way to access overridden modes.

If necessary a template can also provide preamble, a block of code that is executed before every mode call. Unlike scripts, functions, modes, and other blocks, the preamble defaults to the code context instead of the text context, and its output is ignored. Preambles stack through inheritance rather than overriding. The purpose of the preamble is to set up constants and functions for the rest of the template.

The final intrinsic features of a template are its mode permissions lines. This consists of [condition modes: x y z...], where "x y z..." is one or more mode names, separated by spaces, and condition is comment, append, direct, read, edit, or show. There are two usages:


[edit modes: edit submit]
[view modes: view]
[show modes: view edit]

[begin preamble]

// Define a simple function.
// This function updates a counter that reports
// how many times the page has been edited.

increment_edits = function {[
	@_this.edits += 1;
[end preamble]

[begin mode view]
	_body; // display the page's body contents
[end mode view]

[begin mode edit]
	<form method="post">
		<input type="hidden" name="mode" value="submit">
		<!-- passes control to the 'submit' mode when the user clicks 'post' -->
		<input type="hidden" name="id" value="[_id]">
		<!-- makes sure we go to the right submit mode -->
		<textarea name="body">[edit_display(_body)]</textarea>
		<!-- edit_display() converts quotes and angle brackets to HTML entities to prevent breaking input fields -->
		<br><input type="submit" value="Post">
[end mode edit]

[begin mode submit]
	increment_edits(); // call the preamble function
	_body = _params.body; // update the page's parts
				// with the form data

Edit complete.
<a href="./?id=[_id]">Return to the page.</a>
That was edit #[@_this.edits].

[end mode submit]