Spanish Total.js
English
Documentation For AI agents
Contents

Localization

Resource files, @(...) texts, TRANSLATE(), LOCALIZE(), LOADRESOURCE() and the language of a request.

.md GitHub
On this page

Functions, delegates and files of the localization: resource files, @(...) texts, TRANSLATE(), LOCALIZE(), the language of a request and the total5 translate command. The guide Localization explains how they work together with examples; this page is the exact reference.

API

type

/resources/{name}.resource

A text file with a dictionary of translations.

Every .resource file in /resources/ and its subfolders is loaded when the application starts. The file name without the extension is the name of the dictionary (sk.resource is sk). Paths that contain -bk or _bk are skipped.

Each line is key : value. The separator is the first :, or the first = when the line has no :; the value starts at the second character after the separator, so keep one space there. Keys and values are trimmed. Empty lines and lines that start with # or // are ignored. Keys of @(...) texts are T and a hash of the text; other keys are any names you read with F.resource().

sk.resource
# Slovak
T1bx8wg2      : Vitajte
T1oapati      : Pridať do košíka
name          : Meno
January       : január
type

/resources/default.resource

The fallback dictionary.

When a key is missing in the dictionary of the language, or the language has no dictionary, the key is read from the dictionary default. An empty language (the default of a request) reads default directly.

Fallback
// /resources/default.resource contains: name : Name
F.resource('de', 'name'); // 'Name' when de.resource has no "name"
type

'T' + text.hash(true).toString(36)

How the key of an @(...) text is created.

The key is T followed by the unsigned hash of the text inside @(...) in base 36. The same text always has the same key, so the same text in many places needs one translation. Changing the original text changes the key. The total5 translate command creates the keys for you.

Compute a key
var key = 'T' + 'Welcome'.hash(true).toString(36); // 'T1bx8wg2'
command

@(text)

Marks a text for translation.

The text is replaced by its translation from the dictionary of the current language, with a fallback to default. Without a translation the text is printed as it is (without @( and )). Parentheses inside the text must be balanced. It works in views, static .html files, TRANSLATE(), error messages, e-mail subjects and bodies and templates. In views it is replaced before the view is compiled, so it holds plain text only.

In a view
<h1>@(Welcome)</h1>
<p>@(Free delivery (over 50 EUR))</p>
In code
$.invalid('@(The name is required)');
method

LOADRESOURCE(name, [text])

Parses the text of a resource file and stores it as a dictionary.
ParameterTypeDescription
name String The name of the dictionary, usually a language code.
text? String The content in the resource format.

The text has the format of a .resource file. The dictionary replaces a dictionary of the same name as a whole. It is the same function as F.loadresource().

Load a dictionary
LOADRESOURCE('sk', 'T1bx8wg2 : Vitajte\nname : Meno');
From a file of your own
LOADRESOURCE('de', F.Fs.readFileSync(PATH.root('lang/de.txt'), 'utf8'));
method

LOADRESOURCE(url)

Downloads dictionaries from a URL.
ParameterTypeDescription
url String The URL of a JSON response with dictionaries.

Without the second argument the first argument is a URL. The response must be JSON. An object is read as { name: text }, where every text is in the resource format. An array is read as items with the name in id, key, code or language and the text in value, name, text or body. Every dictionary is loaded with LOADRESOURCE(name, text). A failed request throws an error.

Remote dictionaries
// response: { "sk": "T1bx8wg2 : Vitajte", "de": "T1bx8wg2 : Willkommen" }
LOADRESOURCE('https://example.com/translations.json');
method

TRANSLATE(language, text)

Translates all @(...) texts in a string.
ParameterTypeDescription
language String The name of the dictionary. An empty string uses default.
text String A string with @(...) texts.

Returns String The translated string.

Every @(...) is replaced by its translation from the dictionary of the language, with a fallback to default; a text without a translation stays without the brackets. The rest of the string is not changed. It is the same function as F.translate().

Translate a string
TRANSLATE('sk', '<b>@(Welcome)</b>, Peter'); // '<b>Vitajte</b>, Peter'
In a route
function detail($) {
	$.plain(TRANSLATE($.language, '@(Order) #' + $.params.id));
}
method

F.resource(language, key)

Reads one key of a dictionary.
ParameterTypeDescription
language String The name of the dictionary.
key String The key.

Returns String The value, or an empty string when the key does not exist.

Reads the key from the dictionary of the language, then from default. Use it for keys with your own names, not for @(...) texts.

Read a key
// /resources/de.resource contains: currency : EUR
var currency = F.resource('de', 'currency') || 'USD';
property

F.resources

All loaded dictionaries.

Returns Object

An object with the dictionaries by their names. Each dictionary is a plain object of keys and values.

List the languages
var languages = Object.keys(F.resources); // ['default', 'sk', 'de']
method

LOCALIZE(fn)

Registers the delegate that chooses the language of a request.
ParameterTypeDescription
fn Function function($) that returns the language as a string.

The function gets the controller and returns the language (a dictionary name). It is called for routes after the authorization and before the middleware, for static .html files and for WebSocket routes. For HTTP routes and static files it is not called when the language is already set. The result is stored in $.language. It sets DEF.onLocalize.

From the query string or the browser
LOCALIZE(function($) {
	var language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();
	return language === 'sk' || language === 'de' ? language : 'en';
});
From the user
LOCALIZE(function($) {
	return $.user ? $.user.language : 'en';
});
delegate

DEF.onLocalize = function($) {}

The delegate that LOCALIZE() sets.

LOCALIZE(fn) stores the function here. You can also assign it directly; set it to null to stop choosing the language.

Assign directly
DEF.onLocalize = function($) {
	return $.cookie('language') || 'en';
};
property

$.language

The language of the request.

Returns String

An empty string by default, or the value that the LOCALIZE() delegate returned. In a route $ is the controller and you can assign a new language; a view takes the language when you call $.view(), so assign it before.

Set the language in a route
exports.install = function() {
	ROUTE('GET /sk/', index_sk);
};

function index_sk($) {
	$.language = 'sk';
	$.view('index');
}
property

$.language

The language of the request that called the action.

Returns String

In actions and schemas $ is an options object. $.language returns the language of its controller, or an empty string when the action was called without a request. It is read-only.

Translate in an action
NEWACTION('Orders/read', {
	name: 'Read an order',
	action: function($) {
		$.callback({ title: TRANSLATE($.language, '@(Your order)') });
	}
});
property

view.language

The language of a view.

Returns String

A view created for a request takes the language of the request. For F.view() set it in the prepare function. Views are compiled and cached per name and language.

Render a view in German
var html = F.view('mail/order', { id: 'A100' }, function(view) {
	view.language = 'de';
});
command

@{language}

Prints the language of the view.

Prints the language of the request ($.language) as it is (an empty string by default, and always empty in F.view()). The variable language is available in all view expressions.

HTML lang attribute
<html lang="@{language || 'en'}">
type

/public/*.html

Static HTML files are translated too.

An .html file from /public/ is translated into the language of the request (LOCALIZE() is called for it) and cached per language. Files whose name contains .min, -min or @min are sent as they are.

A static page
<!-- /public/about.html -->
<h1>@(About us)</h1>
command

total5 translate [filename]

Creates a resource file with all @(...) texts of a project.
ParameterTypeDescription
filename? String The output file. Default: translate.resource

Reads all .js and .html files in the current directory and its subfolders, collects every @(...) text and writes key : text lines into the file. The default file is translate.resource in the current directory. Copy the result into /resources/ under the name of a language and translate the values.

Create a dictionary
cd my-app
total5 translate resources/sk.resource
The result
T1bx8wg2     : Welcome
T1oapati     : Add to cart
method

errorbuilder.output([language])

Returns the errors translated into a language.
ParameterTypeDescription
language? String The name of the dictionary. Default: 'default'

Returns Array Objects with name, error, path and index.

A message in @(...) is translated. A field error from a schema validation is read from the resources by the name of the field; without that key the message is The field "name" is invalid. The framework calls it with the language of the request when it sends errors.

Translate errors
var err = new ErrorBuilder();
err.push('@(The name is required)');
err.output('sk'); // [{ error: 'Meno je povinné', ... }]
method

errorbuilder.toString([language], [divider])

Returns the translated messages as one string.
ParameterTypeDescription
language? String The name of the dictionary. Default: 'default'
divider? String The text between messages. Default: '\n'

Returns String

Joins the messages of output(language) with the divider.

One line
var text = err.toString('sk', ', ');
type

{field} : message

Translated messages for invalid fields.

When a field fails the validation of a schema, the message is read from the resources with the name of the field as the key, in the language of the request and then in default. Without that key the message is The field "{name}" is invalid.

Messages for fields
# /resources/default.resource
email : Enter a valid e-mail address
name  : Enter your name
method

MAIL(email, subject, view, model, [language], [callback])

Sends an e-mail rendered from a view in a language.
ParameterTypeDescription
email String The recipient.
subject String The subject; it can contain @(...).
view String The name of the view.
model Object The model of the view.
language? String The language.
callback? Function function(err).

With a language, @(...) texts in the subject are translated and the view is rendered with that language. The callback can also come before the language. The Mail guide explains sending.

A localized e-mail
MAIL(user.email, '@(Your order)', 'mail/order', order, user.language);
method

HTMLMAIL(email, subject, body, [language], [callback])

Sends HTML as an e-mail, translated into a language.
ParameterTypeDescription
email String The recipient.
subject String The subject.
body String The HTML body.
language? String The language.
callback? Function function(err).

With a language, @(...) texts in the subject and the body are translated.

Translated body
HTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for your registration)</p>', 'sk');
method

TEMPLATE(body, [model], [$])

Renders a template translated into the language of $.
ParameterTypeDescription
body String The template, its file name or a URL.
model? Object The model.
$? Object The controller or action options with the language.

Returns Promise The rendered HTML.

When you pass $, @(...) texts in the template are translated into $.language before the template is compiled, and the compiled template is cached per language.

In an action
NEWACTION('Orders/print', {
	name: 'Print an order',
	action: async function($) {
		var html = await TEMPLATE('invoice', { number: 'F001' }, $);
		$.callback(html);
	}
});
method

date.format(format, [dictionary])

Formats a date with month and day names from a dictionary.
ParameterTypeDescription
format String The format, for example dddd d. MMMM yyyy.
dictionary? String The name of the dictionary.

Returns String

MMMM and MMM print the month name, dddd and ddd the day name. With a dictionary, the English name (January, Monday) is the key; without a translation the English name is used. MMM prints the first three characters and ddd the first two in upper case.

Slovak names
// sk.resource: January : január, Monday : pondelok
new Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // 'pondelok 1. január'
config

AUTH({ localize: function(data, $) {} })

Sets the language in the built-in session authorization.
ParameterTypeDescription
data Object The session data, or null.
$ Controller The controller of the request.

The built-in session authorization calls localize (or locale) with the session data and the controller and stores the result in $.language. Without a session it is called with null. The LOCALIZE() delegate is then not called. The Authorization guide explains the other options.

Language of the user
AUTH({
	cookie: 'session',
	localize: function(data, $) {
		return data ? data.language : 'en';
	}
	// other options
});
Made in Europe