Views
The view commands, the view object, helpers and TEMPLATE().
On this page
Views are HTML files in /views/ with @{...} commands, rendered by controller.view() and F.view(). This page lists every command, the methods of the view object, the helpers and TEMPLATE(). The guide Views explains how they work together, with examples.
API
method
controller.view([name], [model])
Renders a view and sends it as the HTML response.
controller.view([name], [model])| Parameter | Type | Description |
|---|---|---|
name? |
String |
The name of the view without .html, for example products/detail. |
model? |
Object |
The model, available as model in the view. |
Returns View The view object.
The view is read from /views/{name}.html, or from /plugins/ when the name starts with #. It is rendered into the layout that was set with controller.layout() (or layout by default) and sent with controller.html(). Without a name the method only returns a new view object, which you render yourself.
exports.install = function() {
ROUTE('GET /products/{id}/', detail);
};
function detail($) {
var id = $.params.id;
$.view('products/detail', { id: id });
}
function preview($) {
var view = $.view();
view.layout('');
$.html(view.render('preview', { name: 'Test' }));
}
method
controller.layout(name)
Sets the layout for the next controller.view().
controller.layout(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the layout view. |
Call it before controller.view(). An empty string keeps the default layout; for a view without a layout use @{layout('')} in the view or view.layout(''). A view can still change it with @{layout()}.
function admin($) {
$.layout('layout-admin');
$.view('admin/index');
}
method
F.view(name, [model], [prepare])
Renders a view outside of a request and returns the HTML.
F.view(name, [model], [prepare])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the view. |
model? |
Object |
The model. |
prepare? |
Function |
function(view) called before the rendering, to set view.language, view.repository or the layout. |
Returns String The rendered HTML.
The view has no controller, so controller, user, query and the other request values are empty. The view is rendered into its layout as usual; use @{layout('')} in the view, or view.layout('') in prepare, for a fragment without a layout.
var html = F.view('mail/order', { id: 'A100' }, function(view) {
view.language = 'sk';
view.layout('');
});
class
new F.TViewEngine.View([controller])
The object that renders a view; it is self inside the compiled view.
new F.TViewEngine.View([controller])| Parameter | Type | Description |
|---|---|---|
controller? |
Controller |
The controller of the request. |
controller.view() and F.view() create it for you. Its properties are controller, model, repository ({ layout: 'layout' } at the start), language, url and query. Its methods are the view commands: layout(), title(), description(), keywords(), meta(), json(), href(), import(), section(), helper(), hostname() and view().
function page($) {
var view = $.view();
view.repository.menu = 'products';
$.html(view.render('products', { items: [] }));
}
method
view.render(name, [model])
Renders a view with its layout and returns the HTML.
view.render(name, [model])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the view. |
model? |
Object |
The model. |
Returns String The HTML.
The file is /views/{name}.html (or /plugins/{name}.html for a name with #). When repository.layout is not empty, the result is rendered into that layout.
var view = new F.TViewEngine.View();
view.layout('');
var html = view.render('fragments/card', { name: 'Pen' });
property
view.repository
An object shared by the view, its partial views and the layout.
view.repositoryReturns Object
It holds layout, title, description, keywords, the sections (section_{name}) and any values you add. In the view it is the variable repository. Use it to pass values from a view to its layout.
<!-- view -->
@{repository.menu = 'products'}
<!-- layout -->
<nav class="@{repository.menu}">...</nav>
property
view.language
The language used for @(...) translations.
view.languageReturns String
It is the language of the request in controller.view() and an empty string in F.view(). Set it before rendering; each language has its own compiled copy of the view, and @{language} prints it.
var html = F.view('mail/welcome', model, function(view) {
view.language = 'de';
});
command
@{expression}
Prints the value of a JavaScript expression, HTML-encoded.
@{expression}Any expression works: properties, method calls, operators. null and undefined print as an empty string. An assignment (=, +=, ++…) to model, repository, config, query, user, session or controller is evaluated and prints nothing. @{print(...)} and @{console.log(...)} print nothing in the HTML.
<h1>@{model.name}</h1>
<p>@{model.items.length} items</p>
<p>@{model.price.format(2)}</p>
@{repository.count = model.items.length}
command
@{!expression}
Prints the value of an expression without HTML encoding.
@{!expression}Use it for HTML you trust, for example content of a CMS stored by your administrators.
<article>@{!model.body}</article>
command
@{model}
The model passed to the view.
@{model}It is the second argument of controller.view(), F.view(), view.render() or @{view()}. The layout does not receive the model.
<h1>@{model.title}</h1>
@{if model.user}<p>@{model.user.name}</p>@{fi}
command
@{repository}
The shared object of the view, its partial views and the layout.
@{repository}See view.repository. Assign values with @{repository.key = value}; the assignment prints nothing.
@{repository.menu = 'contact'}
<li class="@{repository.menu === 'contact' ? 'active' : ''}">Contact</li>
command
@{config.key} / @{'%key'}
Prints a configuration value.
@{config.key} / @{'%key'}config is CONF, read on every render. @{'%key'} reads the value once, when the view is compiled, and puts it into the view as text.
<title>@{config.name}</title>
<footer>@{'%name'} @{config.version}</footer>
command
@{query} / @{body} / @{files} / @{user} / @{session} / @{controller}
The data of the current request.
@{query} / @{body} / @{files} / @{user} / @{session} / @{controller}query is the parsed query string, body the parsed body, files the uploaded files, user and session the values of your authorization, and controller the controller itself. In F.view() they are empty. In a layout, @{body} without a property prints the HTML of the view instead.
@{if user}
<p>Hello @{user.name}</p>
@{else}
<a href="/login/">Sign in</a>
@{fi}
<input name="q" value="@{query.q}" />
command
@{body}
In a layout, prints the HTML of the rendered view.
@{body}The output is not encoded. With a property (@{body.name}) it reads the body of the request instead.
<!DOCTYPE html>
<html>
<head>@{import('meta')}</head>
<body>
@{body}
</body>
</html>
command
@{language}
The language of the view.
@{language}The language of the view (view.language): the language of the request (controller.language) in controller.view(), the value you set in the prepare function of F.view(), and an empty string by default.
<html lang="@{language || 'en'}">
var html = F.view('mail/welcome', model, function(view) {
view.language = 'de';
});
// <html lang="de">
command
@{url}
The URL path of the current request.
@{url}It is controller.url, the path as requested (the letter case is kept) with a trailing slash and without the query string. url also works inside expressions and conditions: @{if url === '/'}. In F.view() there is no request: @{url} prints an empty string and url in an expression is undefined.
<a href="/products/" class="@{url === '/products/' ? 'active' : ''}">Products</a>
command
@{hostname([path])}
Prints the absolute URL of the current page or of another path.
@{hostname([path])}| Parameter | Type | Description |
|---|---|---|
path? |
String |
A path that starts with /. Without it, the path of the current request. |
Returns String The absolute URL.
@{hostname()} prints the protocol, the host and the path of the current request, without the query string (https://shop.example.com/products/). @{hostname('/img/share.png')} prints the protocol and the host with the given path. It calls controller.hostname(), see Controller. Write the parentheses: @{hostname} alone does not call the function.
In F.view() there is no request, so it prints only path (or an empty string).
<link rel="canonical" href="@{hostname()}" />
<meta property="og:image" content="@{hostname('/img/share.png')}" />
command
@{cookie(name)}
Prints the value of a cookie of the request, HTML-encoded.
@{cookie(name)}| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the cookie. |
Without a controller it prints an empty string.
<body class="theme-@{cookie('theme')}">
command
@{now}
A new Date with the current time.
@{now}Use properties and methods of the date directly: @{now.getFullYear()}.
<footer>© @{now.getFullYear()} @{config.name}</footer>
command
@{root}
Prints CONF.$root without its trailing slash.
@{root}Use it for links when the application runs under a sub-path. It prints an empty string when CONF.$root is not set.
<a href="@{root}/products/">Products</a>
command
@{if condition} ... @{else if condition} ... @{else} ... @{fi}
Renders a part of the view only when a condition is true.
@{if condition} ... @{else if condition} ... @{else} ... @{fi}The condition is any JavaScript expression. @{endif} is the same as @{fi}. @{if(condition)} with parentheses works as well.
@{if model.stock > 10}
<b>In stock</b>
@{else if model.stock > 0}
<b>Last pieces</b>
@{else}
<b>Sold out</b>
@{fi}
command
@{foreach item in source} ... @{end}
Repeats a part of the view for every item of an array or an object.
@{foreach item in source} ... @{end}For an object, each item is { key, value }. An empty source renders nothing. @{foreach var item in source} works as well. Inside the loop, @{index} is the zero-based position, and @{continue} and @{break} skip an item or stop the loop. Loops can be nested.
<ul>
@{foreach item in model.items}
@{if item.hidden}@{continue}@{fi}
<li>@{index + 1}. @{item.name}</li>
@{end}
</ul>
@{foreach prop in model.settings}
<dt>@{prop.key}</dt><dd>@{prop.value}</dd>
@{end}
command
@{index}
The zero-based position of the current item in @{foreach}.
@{index}@{foreach row in model.rows}
<tr class="@{index % 2 ? 'odd' : 'even'}"><td>@{index + 1}</td><td>@{row.name}</td></tr>
@{end}
command
@{layout(name)}
Sets the layout of the view.
@{layout(name)}| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the layout view, or an empty string. |
The default layout is layout (/views/layout.html). An empty string renders the view without a layout. The command prints nothing.
@{layout('layout-print')}
<h1>@{model.title}</h1>
@{layout('')}
<div class="card">@{model.name}</div>
command
@{view(name, [model])}
Renders another view in place (a partial view).
@{view(name, [model])}| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the view. |
model? |
Object |
The model of the partial view. |
The partial view gets its own model and no layout. It shares repository and the sections with the view that renders it. A name that starts with # reads the file from /plugins/.
@{foreach item in model.items}
@{view('partials/card', item)}
@{end}
@{view('#blog/sidebar')}
command
@{section name} ... @{end} / @{section(name)}
Collects HTML in a view and prints it in another place, usually the layout.
@{section name} ... @{end} / @{section(name)}@{section name} … @{end} adds its HTML to the section; several blocks with the same name are joined. @{section('name')} prints the section, or nothing when it is empty. The section must be filled before it is printed, which is the case for a layout.
<!-- view -->
@{section scripts}
<script src="/js/chart.js"></script>
@{end}
<!-- layout, before </body> -->
@{section('scripts')}
method
view.section(name, [value], [replace])
Reads or fills a section from JavaScript.
view.section(name, [value], [replace])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the section. |
value? |
String |
The HTML to add. |
replace? |
Boolean |
Replace the current content. Default: false |
Returns String|View The section when reading; the view when writing.
Without value it returns the HTML of the section. With value it appends the HTML to the section, or replaces it when replace is true.
function page($) {
var view = $.view();
view.section('scripts', '<script src="/js/page.js"></script>');
$.html(view.render('page'));
}
command
@{title(value)} / @{title}
Sets or prints the title of the page.
@{title(value)} / @{title}| Parameter | Type | Description |
|---|---|---|
value |
String |
The title. |
@{title('Text')} stores the text in repository.title and prints nothing. @{title} prints it HTML-encoded, @{!title} without encoding.
@{title('Products / ' + model.category)}
<h1>@{title}</h1>
command
@{title2(value)}
Appends text to the title of the page.
@{title2(value)}| Parameter | Type | Description |
|---|---|---|
value |
String |
The text to append. |
Adds value to the end of repository.title (or sets it when there is no title yet) and prints nothing. Like title(), the text is stored as it is and encoded once when it is printed. An empty value changes nothing.
@{title('Products')}
@{if model}@{title2(' / ' + model.name)}@{fi}
<h1>@{title}</h1> <!-- Products / Pen & paper -->
command
@{description(value)} / @{description}
Sets or prints the description of the page.
@{description(value)} / @{description}| Parameter | Type | Description |
|---|---|---|
value |
String |
The description. |
The value goes to repository.description; @{import('meta')} prints it as a <meta name="description"> tag.
@{description('Pens, pencils and paper for the office.')}
command
@{keywords(value)} / @{keywords}
Sets or prints the keywords of the page.
@{keywords(value)} / @{keywords}| Parameter | Type | Description |
|---|---|---|
value |
String|Array |
The keywords. |
An array is joined with , . The value goes to repository.keywords.
@{keywords(['pens', 'paper', 'office'])}
command
@{meta([title], [description], [keywords], [image])} / @{meta}
Sets the title, description, keywords and image at once, or prints the meta tags.
@{meta([title], [description], [keywords], [image])} / @{meta}| Parameter | Type | Description |
|---|---|---|
title? |
String |
The title. |
description? |
String |
The description. |
keywords? |
String|Array |
The keywords. |
image? |
String |
An absolute URL or a path of an image. |
With arguments it stores the values in repository as they are and prints nothing; they are HTML-encoded once, when the tags are printed. Without arguments it prints the same tags as @{import('meta')}: <title>, the description and keywords tags, and og:image and twitter:image for the image. A relative image gets the host name of the request; without a request no image tags are printed. The title gets - and CONF.name appended, except on the URL / and when CONF.$customtitles is true; without a title it is CONF.name.
<!-- view -->
@{meta(model.name, model.summary, model.tags, model.photo)}
<!-- layout -->
<head>@{meta}</head>
config
CONF.$customtitles
Prints the page title without the application name.
CONF.$customtitlesReturns Boolean Default false.
By default the title tag of @{meta} and @{import('meta')} is Title - CONF.name. With true the title is printed as you set it.
$customtitles : true
command
@{import(name, [name2], ...)}
Prints the tags for static files, the meta tags or a favicon.
@{import(name, [name2], ...)}| Parameter | Type | Description |
|---|---|---|
name |
String |
A file name, meta or a favicon name. |
Each argument gives one tag:
metaprints the meta tags (see@{meta}).favicon.ico,favicon.pngorfavicon.gifprints a<link rel="icon">tag.- A name with
.cssprints a stylesheet link from/css/, other names a script from/js/. A path that starts with/(or a virtual route) is used as it is. - An
@before the name appends?ts=with the start time of the application. - Names joined with
+are merged into one minified file (see the next entry).
The tags are cached, so the command is cheap.
<head>
@{import('meta', 'favicon.ico', '@default.css', 'ui.js', '/vendor/editor.js')}
</head>
command
@{import('a.css + b.css')}
Merges several CSS or JavaScript files into one minified file.
@{import('a.css + b.css')}The names joined with + are merged with MERGE() into a file with a generated name, such as /xkcqdmatno-min.css, which the framework serves. A name with .css makes a stylesheet, otherwise a script. A file name is looked up in /public/css/ or /public/js/ by its extension, a path that starts with / in /public/, and a URL is downloaded. An @ at the start appends ?ts=.
@{import('reset.css + layout.css + forms.css', '@ui.js + app.js')}
<!-- <link rel="stylesheet" href="/wqxjrnefjv-min.css" /> -->
<!-- <script src="/wbxyamtxmw-min.js?ts=mwi48bh6"></script> -->
command
@{json(value, [id], [beautify], [replacer])}
Prints a value as JSON, or in a <script type="application/json"> tag.
@{json(value, [id], [beautify], [replacer])}| Parameter | Type | Description |
|---|---|---|
value |
Object |
The value. |
id? |
String |
The id of the script tag. |
beautify? |
Boolean |
Indent the JSON. Default: false |
replacer? |
Function|Boolean |
A replacer for JSON.stringify(). |
With id the JSON is wrapped in a script tag with that id, which client code reads without a second request. beautify indents the JSON with four spaces. replacer is a function for JSON.stringify(), or true for the framework replacer. @{json(value, true)} is the same as @{json(value, null, true)}.
@{json(model.products, 'products')}
<script>
var products = JSON.parse(document.getElementById('products').innerHTML);
</script>
command
@{href([key], [value])}
Prints the current query string with one parameter changed.
@{href([key], [value])}| Parameter | Type | Description |
|---|---|---|
key? |
String|Object |
The name of the parameter, or an object with the parameters to set. |
value? |
Any |
The new value. |
Returns String The query string with ?, or an empty string.
@{href} prints the current query string (?page=2&sort=name). @{href('page', 3)} prints it with page set to 3; without a value the current value is kept. More arguments after the value are names of parameters to remove. An array value writes the parameter once for each item (tag=a&tag=b) and an object value is written as JSON. @{href({ page: 3, sort: 'price' })} returns the URL of the request with the query string changed by the keys of the object. Use it for paging and sorting links.
<a href="@{href('page', model.page - 1)}">Previous</a>
<a href="@{href('page', model.page + 1)}">Next</a>
<!-- /products/?page=2&sort=name&q=pen -->
<a href="@{href('page', 1, 'sort')}">First page</a> <!-- ?page=1&q=pen -->
<a href="@{href({ page: 1, sort: 'price' })}">By price</a> <!-- /products/?page=1&sort=price&q=pen -->
property
DEF.helpers
Custom functions you call from every view.
DEF.helpersReturns Object
Add functions to the object; inside a helper this is the view (this.model, this.repository, this.controller). Call a helper by its name (@{price(10)}), with @{helpers.price(10)} or with @{helper('price', 10)}. The returned value is printed without encoding. Register the helpers before the views are compiled, for example in /definitions/.
// /definitions/helpers.js
DEF.helpers.price = function(value, currency) {
return value.format(2) + ' ' + (currency || 'EUR');
};
// in a view: <span>@{price(model.price, 'USD')}</span>
command
@{helper(name, [arg1], [arg2], ...)}
Calls a helper from DEF.helpers by its name.
@{helper(name, [arg1], [arg2], ...)}| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the helper. |
The other arguments go to the helper. It prints an empty string when the helper does not exist.
<span>@{helper('price', model.price, 'EUR')}</span>
command
@(text)
Translates a text into the language of the view.
@(text)The text is replaced by its translation from the resource files when the view is compiled; a text without a translation stays as it is. The Localization guide explains the resources.
<h1>@(Welcome)</h1>
<button>@(Add to cart)</button>
command
@{compile [name]} ... @{end}
Passes a part of the view to DEF.onViewCompile on every render.
@{compile [name]} ... @{end}The HTML between the tags, with the commands already evaluated, is passed to DEF.onViewCompile(name, html, model), and its result is printed. Use it to run Markdown or another processor on a part of the view.
@{compile markdown}
# @{model.title}
@{model.text}
@{end}
delegate
DEF.onViewCompile = function(name, html, model)
Processes the content of @{compile} blocks.
DEF.onViewCompile = function(name, html, model)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the block, or an empty string. |
html |
String |
The content of the block. |
model |
Object |
The model of the view. |
Returns String The HTML to print.
name is the word after @{compile, html the rendered content of the block and model the model of the view. Return the HTML to print. By default it returns html unchanged.
DEF.onViewCompile = function(name, html, model) {
return name === 'markdown' ? html.markdown() : html;
};
event
ON('$view', function(meta) {})
Changes the source of a view before it is compiled.
ON('$view', function(meta) {})| Parameter | Type | Description |
|---|---|---|
meta |
Object |
{ name, body, debug }. |
meta.name is the name of the view, meta.body its HTML source and meta.debug the debug mode. Change meta.body to change the view; the event runs every time a view is compiled.
ON('$view', function(meta) {
meta.body = meta.body.replace(/\{year\}/g, new Date().getFullYear() + '');
});
command
@{nocompress html|js|css|all}
Turns off a compression step for the view.
@{nocompress html|js|css|all}When a view is compiled, runs of spaces inside its text are collapsed (line breaks and indentation between tags are kept), and the CSS of <style> tags and the JavaScript of <script> tags are minified. html keeps the HTML as it is and also turns off the minification of the response; js (or script, javascript) and css (or style) keep the inline code; all turns off all three. HTML comments are always removed.
@{nocompress html}
<pre>
formatted
text
</pre>
command
@{{ text }}
Prints @{{ ... }} as it is, without running it.
@{{ text }}Use it to keep @{{ }} text for client-side templates.
<code>@{{ value }}</code>
method
TEMPLATE(body, [model], [$])
Renders a Tangular template and returns a promise with the HTML.
TEMPLATE(body, [model], [$])| Parameter | Type | Description |
|---|---|---|
body |
String |
The template, a URL, a path or a name of a file in /templates/. |
model? |
Object |
The model, available as value. |
$? |
Options |
The $ of an action or a controller, for the language and error handling. |
Returns Promise<String> The rendered HTML.
body is the template text when it contains {{. Otherwise it is a URL (http:// or https://, downloaded), ~ and an absolute path, # and a path of a file in /plugins/ (.html is added when missing), or a name of a file in /templates/ (.html is added when missing). In the template the model is value.
The template can contain a <script type="text/json"> block with a default model, used when model is not given, and a <script> block that adds helpers to Thelpers. With $ (the $ of a route or an action) the template is translated into $.language, and errors go to $.invalid() instead of rejecting the promise. Templates read from files are cached in release mode.
var html = await TEMPLATE('<p>Hello {{ value.name }}</p>', { name: 'Peter' });
exports.install = function() {
ROUTE('GET /invoice/{id}/', invoice);
};
function invoice($) {
TEMPLATE('invoice', { number: $.params.id }, $).then(function(html) {
$.html(html);
});
}
command
{{ value }} / {{ if }} / {{ foreach }}
The commands of Tangular templates used by TEMPLATE().
{{ value }} / {{ if }} / {{ foreach }}{{ value.name }} prints an HTML-encoded value. {{ if condition }} … {{ else if condition }} … {{ else }} … {{ fi }} is a condition. {{ foreach item in value.items }} … {{ end }} is a loop with {{ $index }}, {{ continue }} and {{ break }}. A value goes through helpers with |: {{ value.html | raw }}.
<h1>Invoice {{ value.number }}</h1>
{{ if value.items.length }}
<table>
{{ foreach item in value.items }}
<tr><td>{{ $index + 1 }}</td><td>{{ item.name }}</td><td>{{ item.price | format(2) }}</td></tr>
{{ end }}
</table>
{{ else }}
<p>No items</p>
{{ fi }}
property
Thelpers
The helpers of Tangular templates.
ThelpersReturns Object
Built-in helpers: encode (the default for every value; encode('json'), encode('url') change the format), raw (no encoding), format(...) (numbers and dates, like Number.format() and Date.format()), def(text) or empty(text) (prints text, or ---, for an empty value) and pluralize(zero, one, few, other). Add your own in Thelpers, globally or in the <script> block of a template file; this is the object that holds the model in value.
<script type="text/json">{ "name": "Guest" }</script>
<script>
Thelpers.upper = function(value) {
return (value || '').toUpperCase();
};
</script>
<h1>{{ value.name | upper }}</h1>
<p>{{ value.count | pluralize('# items', '# item', '# items', '# items') }}</p>
<p>{{ value.date | format('yyyy-MM-dd') }} {{ value.note | def('none') }}</p>