Localization
Resource files, translation functions, the localization delegate and the translate tool.
On this page
Global functions, delegates, properties, configuration keys, view commands and command-line tools for resource files and translations. 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 key : value lines that holds the texts of one language.
resources/{name}.resourceThe file name without .resource is the name of the resource, usually a language (en, sk). default.resource is the fallback for all languages. Each line holds a key, : and a value. Keep a space after the colon, because the parser skips the first character after :. Lines that start with // or # are comments. Keys T + hash are translations of @(Text) and are created by total4 translate. A resource is joined from files registered with F.register(), then tmp/{name}.resource, then resources/{name}.resource; a later line with the same key wins.
// Slovak texts
title : Moja stránka
error-email : Zadajte platnú e-mailovú adresu
method
RESOURCE([name], key)
Reads a value from a resource file.
RESOURCE([name], key)| Parameter | Type | Description |
|---|---|---|
name? |
String |
The resource name (file name without .resource), usually a language. Default: default |
key |
String |
The key. |
Returns String The value, or an empty string.
With one argument it reads from default.resource. When the key is missing in the named resource, the value from default.resource is used and cached. The result is an empty string when the key exists nowhere. Parsed files are cached in F.resources.
var title = RESOURCE('sk', 'title');
var fallback = RESOURCE('title'); // default.resource
method
TRANSLATE([language], text)
Translates one text the same way as @(Text) in views.
TRANSLATE([language], text)| Parameter | Type | Description |
|---|---|---|
language? |
String |
The resource name. Default: default |
text |
String |
The text in the default language, or #key. |
Returns String The translation or the original text.
The key is T plus the hash of the text. When no translation exists, the original text is returned. A text that starts with # (not followed by a space) is read as a resource key, so TRANSLATE('sk', '#title') is RESOURCE('sk', 'title'). Without a language, default.resource is used.
var msg = TRANSLATE($.language, 'Thank you for your order');
method
TRANSLATOR(language, text)
Replaces every @(...) in a string with its translation.
TRANSLATOR(language, text)| Parameter | Type | Description |
|---|---|---|
language |
String |
The resource name. |
text |
String |
A string with @(...) commands. |
Returns String The translated string.
Uses the same rules as views: @(Text) is translated by hash, @(#key) is read from the resource, quotes are escaped when the command is inside quotes. A text with @{notranslate} is returned without that command and without translation. When the resource of the language does not exist, the texts stay.
var html = TRANSLATOR('sk', '<h1>@(Products)</h1><p>@(#welcome)</p>');
method
LOADRESOURCE(name, value)
Writes a resource into the temporary directory and clears its cache.
LOADRESOURCE(name, value)| Parameter | Type | Description |
|---|---|---|
name |
String |
The resource name, or a URL that returns several resources. |
value? |
String|Object|Array |
The content, an object, an array, or an http(s) URL. |
value can be the content of a resource file (a string), an object { key: value }, or an array of items with id/key/code/language and value/name/text/body. The result is saved as tmp/{name}.resource and joined with resources/{name}.resource, which wins for duplicate keys. LOADRESOURCE(name, url) downloads one resource; LOADRESOURCE(url) downloads an object or an array of several resources. Download errors are thrown.
LOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });
LOADRESOURCE('sk', 'https://example.com/translations/sk.json');
LOADRESOURCE('https://example.com/translations/');
method
LOCALIZE(fn)
Sets the delegate that returns the language of each request.
LOCALIZE(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(req, res, isStaticFile) that returns a language string. |
The function is stored as DEF.onLocale. It receives req, res and, for static files, true. It must return the language, which is saved to req.$language. For WebSocket connections it gets only req.
LOCALIZE(function(req, res) {
var lang = req.query.language || (req.headers['accept-language'] || '').substring(0, 2);
return lang === 'sk' ? 'sk' : 'en';
});
method
LOCALIZE(url, [flags], [minify])
Serves static files of a URL translated into the language of the request.
LOCALIZE(url, [flags], [minify])| Parameter | Type | Description |
|---|---|---|
url |
String |
The URL, for example /docs/*.md. |
flags? |
Array |
File extensions (.md) and nocompress. Default: [] |
minify? |
Boolean |
Minifies HTML. Default: true |
Creates a file route that reads the file, replaces @(...) and returns it. Without an extension in the URL it handles .html, .htm, .md and .txt. HTML is minified unless minify is false or flags contains nocompress. In release mode the result is cached for each language. A URL that starts with # is taken from the sitemap.
LOCALIZE('/docs/*.md');
LOCALIZE('/templates/*.html', ['nocompress']);
delegate
DEF.onLocale = function(req, res, isStaticFile)
The delegate that returns the language of a request; null by default.
DEF.onLocale = function(req, res, isStaticFile)| Parameter | Type | Description |
|---|---|---|
req |
Request |
The request. |
res? |
Response |
The response. |
isStaticFile? |
Boolean |
true for static files. |
Returns String The language, saved to req.$language.
Set it with LOCALIZE(fn) or directly. It is called at the start of a static file request, after authorization for routes (so req.user is known), and when a WebSocket connects (with req only). req.localize() calls it again.
DEF.onLocale = function(req) {
return req.user ? req.user.language : 'en';
};
config
AUTH({ locale: function(user, req) })
since 0.0.57
Option of the built-in session AUTH() that sets the language from the user.
AUTH({ locale: function(user, req) })| Parameter | Type | Description |
|---|---|---|
user |
Object |
The user data from onread, or null. |
req |
Request |
The request. |
Returns String The language.
It is called after the session is read, with the user data (or null when the session is missing or invalid) and the request. The returned value is saved to req.$language.
AUTH({
secret: 'my-secret',
cookie: 'session',
onread: function(meta, next) {
NOSQL('users').one().id(meta.userid).callback(next);
},
locale: function(user, req) {
return user ? user.language : 'en';
}
});
property
controller.language
The language of the controller; views and e-mails use it.
controller.languageReturns String
It is set from req.$language when the controller is created, so it is undefined without a localization delegate. You can assign another value before you render a view. Views are compiled and cached for each language. client.language in WebSocket controllers works the same way.
exports.install = function() {
ROUTE('GET /{lang}/', home);
};
function home(lang) {
this.language = lang;
this.view('index');
}
property
req.language
The language of the request.
req.languageReturns String
Returns req.$language. When it is not set, it returns the first language of the Accept-Language header in lower case (for example en-us) and keeps it. It can be assigned.
function detail() {
var lang = this.req.language;
this.plain(lang);
}
method
req.localize()
Runs DEF.onLocale again and returns the new language.
req.localize()Returns String The language.
Useful when something that the delegate reads (a cookie, the user) has changed during the request.
function setlanguage() {
this.req.user.language = this.query.lang;
this.language = this.req.localize();
this.redirect('/');
}
property
$.language
The language of the request in schemas, operations, middleware and AUTH().
$.languageReturns String
In schemas and operations it is controller.language (an empty string without a controller). In middleware it is req.$language. In an AUTH() delegate it is req.language, which falls back to Accept-Language, because the localization delegate runs after authorization.
schema.addWorkflow('send', function($) {
var subject = TRANSLATE($.language, 'Your message was received');
$.success(subject);
});
method
@(Text)
Marks text for translation in views and static HTML files.
@(Text)| Parameter | Type | Description |
|---|---|---|
Text |
String |
The text in the default language, or #key. |
The text is replaced with the translation from the resource of the current language when the view is compiled. The key is T plus a hash of the text; when there is no translation, or the resource file of the language does not exist, the original text stays. @(#key) reads a key from the resource directly. Inside quotes, quotes in the translation are escaped.
<h1>@(Products)</h1>
<button title="@(Add to cart)">@(Add)</button>
<p>@(#welcome)</p>
method
@{resource([name], key)}
Prints a value from a resource file in a view, HTML-encoded.
@{resource([name], key)}| Parameter | Type | Description |
|---|---|---|
name? |
String |
The resource name. Default: default |
key |
String |
The key. |
Returns String The value, or an empty string.
It calls RESOURCE(), so without name it reads default.resource. Use the view variable language to read the resource of the current language. @{!resource(...)} prints the value raw.
<p>@{resource('welcome')}</p>
<p>@{resource(language, 'welcome')}</p>
property
@{language}
The language of the request inside a view.
@{language}The view variable language holds req.$language, or an empty string. Use it in expressions, for example in @{resource(language, 'key')} or in the lang attribute.
<html lang="@{language}">
method
@{notranslate}
Turns off translation of @(...) in a view.
@{notranslate}Put it anywhere in the view or in a string passed to TRANSLATOR(). It is removed from the output and the @(...) commands stay untouched. @{nolocalize} does the same.
@{notranslate}
<p>@(This text stays as it is)</p>
method
MAIL(address, subject, view, [model], [language], [callback])
Sends an e-mail rendered from a view, in a given language.
MAIL(address, subject, view, [model], [language], [callback])| Parameter | Type | Description |
|---|---|---|
address |
String|Array |
The recipient or recipients. |
subject |
String |
The subject. |
view |
String |
The view name. |
model? |
Object |
The model of the view. |
language? |
String |
The language. |
callback? |
Function |
function(err). |
Returns MailMessage The message.
With a language, the subject is translated (with TRANSLATOR() when it contains @(, otherwise with TRANSLATE()) and the view is rendered with that language. language and callback can be swapped.
MAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {
err && console.log(err);
});
method
HTMLMAIL(address, subject, body, [language], [callback])
since 0.0.37
Sends a raw HTML e-mail, translated into a given language.
HTMLMAIL(address, subject, body, [language], [callback])| Parameter | Type | Description |
|---|---|---|
address |
String|Array |
The recipient or recipients. |
subject |
String |
The subject. |
body |
String |
The HTML body. |
language? |
String |
The language. |
callback? |
Function |
function(err). |
Returns MailMessage The message.
With a language, the subject is translated and every @(...) in the body is replaced. language and callback can be swapped.
HTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for signing up.)</p>', 'sk');
method
VIEW(name, [model], [layout], [repository], [language])
Renders a view to a string, optionally in a given language.
VIEW(name, [model], [layout], [repository], [language])| Parameter | Type | Description |
|---|---|---|
name |
String |
The view name. |
model? |
Object |
The model. |
layout? |
String |
The layout. |
repository? |
Object |
The repository. |
language? |
String |
The language. |
Returns String The HTML.
The language is used for @(...) in the view. Without it the view is translated with default.resource.
var html = VIEW('mails/invoice', invoice, '', null, 'sk');
method
date.format([format], [resource])
Formats a date; month and day names are read from a resource.
date.format([format], [resource])| Parameter | Type | Description |
|---|---|---|
format? |
String |
The format, for example dddd d. MMMM yyyy. |
resource? |
String |
The resource with names of months and days. Default: default |
Returns String The formatted date.
MMMM and MMM read the English month name (January…December) as a key from the resource, dddd and ddd the day name (Sunday…Saturday). When a key is missing, the English name is used.
// sk.resource: January : január, Monday : pondelok
var text = NOW.format('dddd d. MMMM yyyy', 'sk');
method
builder.resource(name, [prefix])
Sets the resource and the key prefix for error messages.
builder.resource(name, [prefix])| Parameter | Type | Description |
|---|---|---|
name |
String |
The resource name. |
prefix? |
String |
A prefix for keys. Default: '' |
Returns ErrorBuilder The builder.
Errors pushed with a key (builder.push('email')) are read as prefix + name from the resource. The builder then keeps this resource and is not switched to the language of the request.
var builder = new ErrorBuilder();
builder.resource('sk', 'error-');
builder.push('email'); // reads error-email from sk.resource
method
builder.setResource(name)
Sets only the resource for error messages.
builder.setResource(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The resource name. |
Returns ErrorBuilder The builder.
The framework calls it with the language of the request before it sends errors, unless you have set a resource yourself.
var builder = new ErrorBuilder();
builder.setResource('de');
method
builder.setPrefix(prefix)
Sets the prefix of keys for error messages.
builder.setPrefix(prefix)| Parameter | Type | Description |
|---|---|---|
prefix |
String |
The prefix. |
Returns ErrorBuilder The builder.
An error pushed with a name is read as prefix + name from the resource.
var builder = new ErrorBuilder();
builder.setPrefix('error-');
builder.push('name');
method
schema.setResource(name)
Reads the errors of a schema from a fixed resource.
schema.setResource(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The resource name. |
Returns SchemaBuilderEntity The schema.
Without it, errors of the schema are translated with the language of the request.
NEWSCHEMA('Contact', function(schema) {
schema.setResource('errors');
schema.define('email', 'Email', true);
});
method
schema.setPrefix(prefix)
Sets a prefix for resource keys of the schema errors.
schema.setPrefix(prefix)| Parameter | Type | Description |
|---|---|---|
prefix |
String |
The prefix. |
Returns SchemaBuilderEntity The schema.
A required or invalid field email is read as prefix + 'email' from the resource.
NEWSCHEMA('Contact', function(schema) {
schema.setPrefix('contact-');
schema.define('email', 'Email', true); // key: contact-email
});
method
F.register(path)
Adds a .resource file from another location to a resource.
F.register(path)| Parameter | Type | Description |
|---|---|---|
path |
String |
The path to a .resource file. |
The file name gives the resource name, so /modules/shop/sk.resource is added to the sk resource. A path that starts with @ is in a package, = in a theme. Registered files are read before tmp/ and resources/, so the application can override their keys. Other extensions throw an error.
F.register(PATH.root('modules/shop/sk.resource'));
property
F.resources
The cache of parsed resources, by name.
F.resourcesReturns Object
Each value is an object of keys and values. It is cleared every default_interval_clear_resources minutes, and for one name when LOADRESOURCE() or F.register() changes it.
F.resources = {};
method
PATH.resources([filename])
Returns the path of the resources directory or of a file in it.
PATH.resources([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String The absolute path.
var filename = PATH.resources('sk.resource');
config
directory_resources : /resources/
The directory with resource files.
directory_resources : /resources/| Parameter | Type | Description |
|---|---|---|
directory_resources? |
String |
A path relative to the root of the application. Default: /resources/ |
directory_resources : /translations/
config
allow_localize : true
Translates .html and .htm files from public/ with @(...).
allow_localize : true| Parameter | Type | Description |
|---|---|---|
allow_localize? |
Boolean |
Enables translation of static HTML files. Default: true |
The translated files are cached for each language in release mode.
allow_localize : false
config
default_interval_clear_resources : 20
How often, in minutes, the cache of resources is cleared.
default_interval_clear_resources : 20| Parameter | Type | Description |
|---|---|---|
default_interval_clear_resources? |
Number |
Minutes. Default: 20 |
After clearing, resource files are read again on the next use, so changes appear without a restart. The clear event is emitted with resources.
default_interval_clear_resources : 5
config
default_errorbuilder_resource_name : name
The default resource of every new ErrorBuilder.
default_errorbuilder_resource_name : name| Parameter | Type | Description |
|---|---|---|
default_errorbuilder_resource_name? |
String |
The resource name. |
Not set by default. The framework still switches error builders to the language of the request before it sends them.
default_errorbuilder_resource_name : errors
config
default_errorbuilder_resource_prefix : prefix
The default key prefix of every new ErrorBuilder.
default_errorbuilder_resource_prefix : prefix| Parameter | Type | Description |
|---|---|---|
default_errorbuilder_resource_prefix? |
String |
The prefix. Default: '' |
Not set by default (an empty prefix).
default_errorbuilder_resource_prefix : error-
method
total4 translate [path | "text" | filename]
Creates translate.resource with every text to translate.
total4 translate [path | "text" | filename]| Parameter | Type | Description |
|---|---|---|
argument? |
String |
A directory, a text file, or a text. |
Without an argument it scans the current directory (without node_modules, tmp and .git): @(Text) in .html, .js and sitemap files, and in .js also keys of $.invalid('key') and .error('key'). Texts are grouped under comments with the file names. @(#key) is skipped. With a text file, each line becomes one entry. With a text that is not a file, it prints its key.
total4 translate
total4 translate "Add to cart"
method
total4 translatecsv
Writes the texts to translate into translate.csv.
total4 translatecsvThe CSV has the columns Hash;Text;Translation. Fill the last column, then convert it back with total4 csv.
total4 translatecsv
method
total4 csv <filename>
Creates a resource file from a CSV file.
total4 csv <filename>| Parameter | Type | Description |
|---|---|---|
filename |
String |
The CSV file. |
Reads a ;-separated CSV, skips the first row, and uses the first column as the key and the second as the value. The output has the same name with .resource.
total4 csv sk.csv
method
total4 diff <source> <target>
Lists keys to add to and to remove from a resource.
total4 diff <source> <target>| Parameter | Type | Description |
|---|---|---|
source |
String |
The new file, for example translate.resource. |
target |
String |
The translated file. |
Compares the keys of both files and writes <target>-diff.txt with the keys of source that the target does not have and the keys of the target that source does not have.
total4 diff translate.resource resources/sk.resource
method
total4 merge <source> <target>
Copies values from one resource into another.
total4 merge <source> <target>| Parameter | Type | Description |
|---|---|---|
source |
String |
The file with new values. |
target |
String |
The file to update. |
Writes <target>-merged.txt: the lines of the target, with the value of each key replaced by the value from source when it has one.
total4 merge translated.resource resources/sk.resource
method
total4 clean <source>
Aligns the keys and values of a resource file.
total4 clean <source>| Parameter | Type | Description |
|---|---|---|
source |
String |
The resource file. |
Writes <source>-cleaned.txt with all keys padded to the same width and : between key and value.
total4 clean resources/sk.resource