Spanish Total.js
English
Documentation For AI agents
Contents

Views

Every command of the view engine and the controller methods that render views.

.md GitHub
On this page

Views are .html files in views/ with commands in @{...} and translated text in @(...). The guide Views explains how they work together; this page lists each command and the controller methods for views.

API

command

@{expression}

Prints the value of a JavaScript expression, HTML-encoded.
ParameterTypeDescription
expression Any A JavaScript expression.

Returns String The encoded value.

Any expression works: a property of the model, a method call, arithmetic. null and undefined print an empty string. The characters <, >, &, " and ' are encoded. To print the value without encoding, use @{!expression}.

Text that starts with @{{ is not a command and stays in the page as written.

Values of the model
<h1>@{model.name}</h1>
<p>@{model.price.format(2)} EUR</p>
<p>@{model.items.length} items</p>
command

@{!expression}

Prints the value of an expression without HTML encoding.
ParameterTypeDescription
expression Any A JavaScript expression.

Returns String The raw value.

Use it for HTML that you trust, for example content you have already sanitized. Never use it for text typed by users.

Raw HTML
<article>@{!model.html}</article>
command

@{model.property}

The model passed to the view by controller.view(name, model).

M is a shorter name for the same object. The layout gets the same model as the view. A command that assigns a value, like @{model.count = 0}, prints nothing.

Controller and view
function detail(id) {
	this.view('detail', { id: id, name: 'Apple' });
}
In the view
<h1>@{model.name}</h1>
<small>@{M.id}</small>
command

@{repository.property}

An object shared by the view, its partial views and the layout during one request.

It is controller.repository in JavaScript. R is a shorter name. Values set in the view are visible in the layout, because the view is rendered first.

Set in the view, read in the layout
@{repository.page = 'products'}

<!-- layout.html -->
<body class="@{repository.page}">
command

@{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}

Values of the current request that every view can use.
VariableValue
userThe signed-in user (controller.user)
sessionThe session (controller.session)
queryThe query string as an object
bodyThe request body; @{body} alone is the rendered view, in a layout
config, CONFThe configuration
languageThe language of the request
urlThe path of the request
filesUploaded files
mobiletrue for a mobile device
controllerThe controller

They are encoded like any expression; put ! in front for the raw value.

Request values
@{if user}
	<p>Hello @{user.name}</p>
@{fi}
<input type="search" name="q" value="@{query.q}" />
command

@{'%key'}

Prints a value of the configuration, HTML-encoded.
ParameterTypeDescription
key String A key of the configuration.

The value is read when the view is compiled. @{config.key} and @{CONF.key} print the same value. A quoted path without %, like @{'/css/default.css'}, prints the URL of that static file.

App name
<footer>@{'%name'}</footer>
<footer>@{CONF.name}</footer>
command

@{if condition} ... @{else if condition} ... @{else} ... @{fi}

Renders a part of the view only when a condition is true.
ParameterTypeDescription
condition Any A JavaScript expression.

The condition is JavaScript. @{else if} and @{else} are optional. Close the block with @{fi} or @{endif}.

Condition
@{if model.items.length}
	<p>@{model.items.length} products</p>
@{else if model.loading}
	<p>Loading…</p>
@{else}
	<p>No products.</p>
@{fi}
command

@{foreach item in source} ... @{end}

Renders a part of the view for each item of an array or object.
ParameterTypeDescription
item String The name of the variable for the current item.
source Array|Object The expression to loop over.

index is the position of the current item, from 0. An empty source prints nothing. When the source is an object, it becomes an array of { key, value }. @{foreach var item in source} also works. @{continue} and @{break} skip an item or stop the loop.

Array
<ul>
	@{foreach item in model.items}
		<li>@{index + 1}. @{item.name}</li>
	@{end}
</ul>
Object
@{foreach item in model.prices}
	<li>@{item.key}: @{item.value}</li>
@{end}
Skip items
@{foreach item in model.items}
	@{if item.hidden}
		@{continue}
	@{fi}
	<li>@{item.name}</li>
@{end}
command

@{body}

Prints the rendered view inside the layout.

Use it in the layout. With a property, @{body.name} reads the request body instead.

Layout
<!DOCTYPE html>
<html>
<head>
	@{import('meta', 'head', 'default.css')}
</head>
<body>
	@{body}
</body>
</html>
command

@{layout(name)}

Changes the layout of the current view.
ParameterTypeDescription
name String The name of the layout, or '' for no layout.

Returns String An empty string.

The default layout is layout (default_layout in the config). An empty string renders the view without a layout. Layouts are always looked up from the root of views/.

Another layout
@{layout('admin')}

<h1>Dashboard</h1>
No layout
@{layout('')}
command

@{view(name, [model], [expire], [key])}

Renders a partial view in place, without a layout.
ParameterTypeDescription
name String The name of the view.
model? Object The model of the partial view.
expire? String How long to cache the output, e.g. '5 minutes'.
key? String A key that makes the cache entry unique, e.g. the language.

Returns String The rendered HTML.

The name is resolved like in controller.view(). The partial does not get the model of the parent automatically; pass it. With expire the output is cached for that time under the name and the key.

Partial per item
@{foreach item in model.items}
	@{view('partials/product', item)}
@{end}
Cached menu
@{view('menu', model.menu, '10 minutes', language)}
command

@{view_compile(body, [model], [key])}

Compiles an HTML string as a view and renders it in place.
ParameterTypeDescription
body String The template, with the same syntax as a view.
model? Object The model.
key? String A cache key for the compiled template.

Returns String The rendered HTML.

Useful for templates stored in a database. The result has no layout. With key, the compiled template is kept in memory in release mode.

Template from the model
@{view_compile(model.template, model.data)}
command

@{section name} ... @{end} / @{section('name')}

Writes HTML in the view and prints it somewhere else, usually in the layout.
ParameterTypeDescription
name String The name of the section.

@{section name} … @{end} stores its content and prints nothing; blocks with the same name are joined. @{section('name')} prints the stored content, or nothing. The content is kept in the repository, so print it after the view is rendered: in the layout.

Scripts of one page
@{section scripts}
	<script src="/js/chart.js"></script>
@{end}

<h1>Statistics</h1>
In the layout
	@{body}
	@{section('scripts')}
</body>
command

@{helper name(arguments)} ... @{end}

Defines a helper inside the view.
ParameterTypeDescription
name String The name of the helper.
arguments String Names of the arguments, as in a JavaScript function.

The helper exists only in this view. Call it by its name; its output is not encoded again. For helpers shared by all views use DEF.helpers.

Inline helper
@{helper badge(text, color)}
	<span class="badge badge-@{color}">@{text}</span>
@{end}

@{badge('New', 'green')}
@{badge('Sale', 'red')}
property

DEF.helpers.name = function(...args) {}

Defines view helpers available in all views.

Add the functions before the views are compiled, for example in definitions/. In a view, call the helper by its name: @{name(arguments)}; @{helpers.name(arguments)} and @{helper('name', arguments)} work too. Inside the function this is the controller. The returned value is printed without encoding.

Define
// definitions/helpers.js
DEF.helpers.price = function(value, currency) {
	return value.format(2) + ' ' + (currency || 'EUR');
};

DEF.helpers.active = function(path) {
	return this.url === path ? ' class="active"' : '';
};
Use
<span>@{price(item.price, 'USD')}</span>
<a href="/products/"@{active('/products/')}>Products</a>
command

@(Text)

Marks text for translation; it is replaced when the view is compiled.
ParameterTypeDescription
Text String The text in the default language, or #key.

The text is translated with the language of the controller (controller.language, which comes from DEF.onLocale). The translation is read from the resource file of the language under a key made from the hash of the text; when there is none, the original text stays. @(#key) reads key from the resource directly. Inside quotes, quotes in the translation are escaped. Each language gets its own compiled view.

Translated text
<h1>@(Products)</h1>
<button title="@(Add to cart)">@(Add)</button>
<p>@(#footer_note)</p>
command

@{resource([name], key)}

Prints a value from a resource file, HTML-encoded.
ParameterTypeDescription
name? String The resource file without extension. Default: default
key String The key.

Returns String The value, or an empty string.

Without name the value comes from default.resource. When a key is missing in another file, the value from default.resource is used. @{!resource(...)} prints it raw.

Resource values
<p>@{resource('welcome')}</p>
<p>@{resource('en', 'welcome')}</p>
command

@{import(file1, [file2], ...)}

Writes the HTML tags for static files and for the head of the page.
ParameterTypeDescription
file String A file name or one of the keywords. As many as you need.

Returns String HTML tags.

Each argument is one of:

ArgumentOutput
'meta'Title and meta tags, see @{meta}
'head'The author meta tag and the tags added with @{head()}
'file.css'<link rel="stylesheet"> from /css/
'file.js'<script> from /js/
'favicon.ico', 'favicon.png'The icon link
an image or videoIts URL
'a.css + b.css'One merged file with all of them
'manifest'<link rel="manifest">
'livereload'The live reload script, in debug mode only

A name that starts with / or a full URL is used as it is. ! in front of a file prints only its URL. The output is cached per file.

Head of a layout
<head>
	<meta charset="utf-8" />
	@{import('meta', 'head', 'default.css', 'default.js', 'favicon.ico')}
</head>
Merged files
@{import('ui.css + default.css', 'ui.js + default.js')}
command

@{css(file1, [file2], ...)} / @{js(file1, [file2], ...)}

Write <link rel="stylesheet"> tags for CSS files, or <script> tags for JavaScript files.
ParameterTypeDescription
file String A file. As many as you need.

Returns String HTML tags.

Relative names are taken from /css/ (static_url_style) and /js/ (static_url_script). In @{js()}, start a name with async to add the async attribute.

Styles and scripts
@{css('default.css', 'print.css')}
@{js('default.js', 'async stats.js')}
command

@{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}

Prints the URL of a static file in its folder, without a tag.
ParameterTypeDescription
name String The file name.

Returns String The URL.

Each command uses its folder from the config: /js/, /css/, /img/, /videos/, /fonts/, /download/, and public the root. A name that starts with / is used from the root. The URL respects the theme and default_root.

URLs
<img src="@{public_image('logo.png')}" alt="Logo" />
<script src="@{public_js('app.js')}"></script>
command

@{meta} / @{meta(title, [description], [keywords], [image])}

Prints the title and meta tags of the page, or sets them.
ParameterTypeDescription
title? String The title.
description? String The description.
keywords? String|Array Keywords.
image? String An image for social networks, an absolute URL or a file in /img/.

Returns String HTML tags, or an empty string when setting.

Without arguments it prints <title>, the description and keywords meta tags, and og:image and twitter:image when an image is set. With arguments it sets the values and prints nothing. The title gets - and CONF.name at the end unless allow_custom_titles is true. To change the output, replace DEF.onMeta.

Set in the view, print in the layout
@{meta(model.name, model.summary, model.tags, model.picture)}

<!-- layout.html -->
<head>
	@{meta}
</head>
command

@{title} / @{title(value)} / @{title2(value)}

Prints or sets the title of the page.
ParameterTypeDescription
value? String The title.

Returns String The title, or an empty string when setting.

@{title(value)} sets the title and prints nothing; @{title2(value)} appends to the current title. @{title} prints the title alone. The value is HTML-encoded when it is set, so @{!title} prints it without encoding it twice. To print the whole <title> tag, use @{meta}.

Title
@{title(model.name)}

<h1>@{!title}</h1>
command

@{description(value)} @{keywords(value)} @{author(value)}

Sets the description, keywords or author of the page.
ParameterTypeDescription
value? String|Array The value.

Returns String The value, or an empty string when setting.

With an argument they set the value and print nothing. @{description}, @{keywords} and @{author} print the value. @{meta} prints the description and keywords; @{import('head')} prints the author (or CONF.author). Keywords can be an array.

Meta values
@{description('Fresh apples from our farm')}
@{keywords(['apples', 'fruit'])}
@{author('Peter')}
command

@{head} / @{head(value1, [value2], ...)}

Adds CSS, JavaScript or HTML to the head of the page, or prints it.
ParameterTypeDescription
value? String A file name, a URL or HTML.

Returns String HTML, or an empty string when adding.

With arguments it adds tags and prints nothing: .css files become <link>, .js files <script>, and a value that starts with < is added as HTML. Each value is added once. @{head} (or @{import('head')}) prints the author meta tag and everything added.

Add from a view
@{head('chart.css', 'chart.js', '<meta name="robots" content="noindex" />')}
Print in the layout
<head>
	@{import('meta', 'head')}
</head>
command

@{place(name)} / @{place(name, value1, [value2], ...)}

Adds content to a named place, or prints it.
ParameterTypeDescription
name String The name of the place.
value? String A file path or HTML.

Returns String The content, or an empty string when adding.

With values it appends them and prints nothing: .js and .mjs files become <script>, .css files <link>, anything else is added as it is. With the name only it prints the content. Values are not resolved to the static folders, so write full paths.

Place for scripts
@{place('scripts', '/js/chart.js')}

<!-- layout.html -->
@{place('scripts')}
command

@{json(value, [id], [beautify])}

Serializes a value to JSON.
ParameterTypeDescription
value Any The value to serialize.
id? String The id of a <script> element.
beautify? Boolean Indents the JSON. Default: false

Returns String JSON, or a <script> element.

With id the JSON is wrapped in <script type="application/json" id="...">, so client-side code can read it. The output is not HTML-encoded.

Data for the browser
@{json(model.items, 'items')}
<script>
	var items = JSON.parse(document.getElementById('items').innerHTML);
</script>
command

@{options(items, [selected], [name], [value], [disabled])}

Writes <option> elements for a <select>.
ParameterTypeDescription
items Array|Object The options.
selected? Any The value of the selected option.
name? String The property with the text. Default: name
value? String The property with the value. Default: value
disabled? String The property that disables an option. Default: disabled

Returns String HTML.

For an array of objects, name is the property of the text (default name) and value the property of the value (default: the same as name when you give a name, otherwise value). The property disabled disables an option. For an array of strings or numbers, each item is both text and value. For an object, keys are values and values are texts. The option equal to selected gets selected="selected". Texts and values are encoded.

Select
<select name="country">
	@{options(model.countries, model.country, 'name', 'id')}
</select>
Strings
<select name="size">
	@{options(['S', 'M', 'L'], 'M')}
</select>
command

@{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}

Prints an HTML attribute when a condition is true.
ParameterTypeDescription
condition Any When truthy, the attribute is printed.

Returns String The attribute or an empty string.

They print checked="checked", selected="selected", disabled="disabled" or readonly="readonly", with a space in front, or nothing.

Attributes
<input type="checkbox" name="newsletter"@{checked(model.newsletter)} />
<button@{disabled(!model.items.length)}>Order</button>
command

@{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}

Writes an <input> for a field of the model.
ParameterTypeDescription
name String The name of the field.
attributes? Object Extra attributes, e.g. { placeholder: 'Name', required: true }.

Returns String An <input> element.

The model of the view is added automatically: the value of the input is model[name], encoded. The attributes are added to the element; required, disabled, readonly and autofocus are written as boolean attributes, and autocomplete: true writes autocomplete="on" (any other truthy value writes off). value in the attributes is used when the model has no such field.

Form fields
<form method="POST">
	@{text('name', { placeholder: 'Your name', required: true })}
	@{password('password')}
	@{hidden('id')}
</form>
command

@{input(type, name, [attributes])}

since 0.0.53 Writes an <input> of any type for a field of the model.
ParameterTypeDescription
type String The type of the input.
name String The name of the field.
attributes? Object Extra attributes.

Returns String An <input> element.

Works like @{text()} with the type you choose, for example email, number or date.

Email
@{input('email', 'email', { placeholder: 'you@example.com' })}
command

@{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}

Writes a checkbox or a radio button for a field of the model.
ParameterTypeDescription
name String The name of the field.
value String Radio only: the value of this button.
label? String|Object A label, or extra attributes (label is one of them).

Returns String An <input>, wrapped in <label> when there is a label.

A checkbox is checked when model[name] is true, 1, 'true' or 'on'; its value is 1. A radio button is checked when model[name] equals value. A string as the last argument is a label: the input is wrapped in <label> with the text in a <span>. @{radio()} needs this last argument, a label or an object.

Checkbox and radio
@{checkbox('newsletter', 'Send me news')}
@{radio('size', 'S', 'Small')}
@{radio('size', 'L', 'Large')}
command

@{textarea(name, [attributes])}

Writes a <textarea> with the value of a field of the model.
ParameterTypeDescription
name String The name of the field.
attributes? Object Extra attributes, e.g. { rows: 5 }.

Returns String A <textarea> element.

The content is model[name], or value from the attributes. The content is not encoded, so encode values typed by users first.

Textarea
@{textarea('note', { rows: 5, placeholder: 'Note' })}
command

@{image(name, [width], [height], [alt], [class])}

Writes an <img> for a file in /img/.
ParameterTypeDescription
name String The image file.
width? Number|Object The width, or an object with all attributes.
height? Number The height.
alt? String The alternative text.
class? String CSS classes.

Returns String An <img> element.

Instead of the arguments you can pass an object: { width, height, alt, class, style }. alt is encoded.

Image
@{image('logo.png', 120, 40, 'Logo')}
@{image('photo.jpg', { alt: model.name, class: 'photo' })}
command

@{csrf}

since 0.0.37 Prints a CSRF token for the current request.

Returns String The token.

A route with the csrf flag checks the token in the X-CSRF-Token header or in the csrf query parameter. It needs secret_csrf in the config. The token is made by DEF.onCSRFcreate(req) and checked by DEF.onCSRFcheck(req).

Form and AJAX
<form method="POST" action="/contact/?csrf=@{csrf}">
	...
</form>

<meta name="csrf-token" content="@{csrf}" />
command

@{href()} / @{href(key, value)}

Prints the current query string, optionally with one key changed.
ParameterTypeDescription
key? String The parameter to set.
value? Any Its new value.

Returns String A query string.

The result starts with ?, or is empty. Use it for paging and filters that keep the other parameters.

Paging
<a href="@{href('page', model.page + 1)}">Next</a>
command

@{url} / @{url(true)}

Prints the path of the current request.
ParameterTypeDescription
host? Boolean Adds the protocol and the host. Default: false

Returns String The URL.

@{url(true)} prints the full address with the protocol and the host.

Canonical link
<link rel="canonical" href="@{url(true)}" />
command

@{compile name} ... @{end}

Passes a rendered block of the view to DEF.onCompileView().
ParameterTypeDescription
name String A name that tells your function what to do.

The function gets the name, the HTML of the block and the model, and returns the HTML to print. By default it returns the HTML unchanged; replace it to run another template language or a Markdown parser. The block is not minified.

A hook
DEF.onCompileView = function(name, html, model) {
	return name === 'markdown' ? html.markdown() : html;
};
In a view
@{compile markdown}
# Title
Some **text**.
@{end}
command

@{nocompress html|css|js|all}

Turns off the minification of a view.
ParameterTypeDescription
type String html, css, js or all.

By default Total.js minifies the HTML of a view and its inline CSS and JavaScript. Put this command anywhere in the view to keep one part as written: html, css (or style), js (or script, javascript) or all. HTML comments are removed in any case, except conditional comments.

Keep the HTML as written
@{nocompress html}
<pre>
	Indented   text
</pre>
method

controller.view([name], [model], [headers], [partial])

Renders a view with its layout and sends it as the response.
ParameterTypeDescription
name? String The name of the view without .html. Default: from the URL
model? Object The model of the view.
headers? Object Extra HTTP headers.
partial? Boolean true returns the HTML instead of sending it. Default: false

Returns Controller|String The controller, or the HTML when partial is true.

Without name the view is named after the last part of the URL (index for /). The name is looked up in views/<controller>/ first, then in views/; prefixes ~, =theme/, @, #plugin/ and . change that (see the guide). With partial set to true, the method returns the HTML instead of sending it; the layout is still applied unless you set controller.layout(''). When the view does not exist, the response is an error 500.

Render a view
exports.install = function() {
	ROUTE('GET /products/', products);
};

function products() {
	this.view('products', { items: [] });
}
Get the HTML
function preview() {
	this.layout('');
	var html = this.view('card', model, true);
	this.json({ html: html });
}
method

controller.view_compile(body, [model], [headers], [partial], [key])

Compiles an HTML string as a view, renders it and sends it.
ParameterTypeDescription
body String The template.
model? Object The model.
headers? Object Extra HTTP headers.
partial? Boolean true returns the HTML instead of sending it. Default: false
key? String A cache key for the compiled template.

Returns Controller|String The controller, or the HTML when partial is true.

The string uses the same syntax as a view file. With key the compiled template is kept in memory in release mode.

Template from a database
function page() {
	this.layout('');
	this.view_compile('<h1>@{model.title}</h1>', { title: 'Hello' });
}
method

controller.layout(name)

Sets the layout for the next view.
ParameterTypeDescription
name String The name of the layout, or ''.

Returns Controller The controller.

The default is default_layout from the config (layout). An empty string renders without a layout. The view can change it again with @{layout()}.

Admin layout
function dashboard() {
	this.layout('admin');
	this.view('dashboard');
}
method

controller.meta(title, [description], [keywords], [image])

Sets the title and meta tags that @{meta} prints.
ParameterTypeDescription
title String The title.
description? String The description.
keywords? String|Array Keywords.
image? String An image for social networks.

Returns Controller The controller.

controller.title(), controller.description(), controller.keywords() and controller.author() set one value each.

Meta tags
function detail() {
	this.meta('Apple', 'Fresh apples', ['apple', 'fruit'], 'apple.jpg');
	this.view('detail');
}
method

controller.section(name, [value], [replace])

Adds content to a section of the view, or reads it.
ParameterTypeDescription
name String The name of the section.
value? String HTML to add.
replace? Boolean Replaces the content instead of appending. Default: false

Returns Controller|String The controller, or the content when reading.

Without value it returns the content. Otherwise it appends the value, or replaces the content when replace is true. Print the section with @{section('name')}.

Section from a controller
function stats() {
	this.section('scripts', '<script src="/js/chart.js"></script>');
	this.view('stats');
}
property

controller.repository

An object shared by the view, its partial views and the layout.

In the view it is repository or R.

Pass a value to the layout
function products() {
	this.repository.page = 'products';
	this.view('products');
}
method

VIEW(name, [model], [layout], [repository], [language])

Renders a view outside a request and returns the HTML.
ParameterTypeDescription
name String The name of the view.
model? Object The model.
layout? String A layout. Default: ''
repository? Object The repository.
language? String The language for @(...).

Returns String The HTML.

There is no layout unless you name one. Use it for emails, files or responses built by hand. A name like =theme/view reads the view from a theme.

Render to a string
var html = VIEW('emails/order', order, null, null, 'en');
method

VIEWCOMPILE(body, [model], [layout], [repository], [language])

Compiles an HTML string as a view, outside a request, and returns the HTML.
ParameterTypeDescription
body String The template.
model? Object The model.
layout? String A layout. Default: ''
repository? Object The repository.
language? String The language for @(...).

Returns String The HTML.

It is VIEW() for a template in a string, for example from a database. The string uses the same syntax as a view file. There is no layout unless you name one, and layout and repository can switch places. The template is compiled on every call.

Template from a string
var html = VIEWCOMPILE('<h1>@{model.title}</h1>', { title: 'Hello' });
Made in Europe