---
title: Localization
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/localization/
updated: 2026-11-16T15:41:05.817Z
---

# Localization

> Resource files, translation functions, the localization delegate and the translate tool.

Global functions, delegates, properties, configuration keys, view commands and command-line tools for resource files and translations. The guide [Localization](../../guides/localization/) explains how they work together, with examples; this page is the exact reference.

## API

### resources/{name}.resource

Type: `type`

A text file with `key : value` lines that holds the texts of one language.

The 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.

Example: resources/sk.resource
```text
// Slovak texts
title                : Moja stránka
error-email          : Zadajte platnú e-mailovú adresu
```

### RESOURCE([name], key)

Type: `method`

Reads a value from a resource file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | `default` | The resource name (file name without `.resource`), usually a language. |
| `key` | `String` | yes |  | 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`.

Example: Read values
```js
var title = RESOURCE('sk', 'title');
var fallback = RESOURCE('title'); // default.resource
```

### TRANSLATE([language], text)

Type: `method`

Translates one text the same way as `@(Text)` in views.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `language` | `String` | no | `default` | The resource name. |
| `text` | `String` | yes |  | 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.

Example: Translate a message
```js
var msg = TRANSLATE($.language, 'Thank you for your order');
```

### TRANSLATOR(language, text)

Type: `method`

Replaces every `@(...)` in a string with its translation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `language` | `String` | yes |  | The resource name. |
| `text` | `String` | yes |  | 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.

Example: Translate a template
```js
var html = TRANSLATOR('sk', '<h1>@(Products)</h1><p>@(#welcome)</p>');
```

### LOADRESOURCE(name, value)

Type: `method`

Writes a resource into the temporary directory and clears its cache.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The resource name, or a URL that returns several resources. |
| `value` | `String|Object|Array` | no |  | 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.

Example: Load from an object
```js
LOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });
```

Example: Download from a URL
```js
LOADRESOURCE('sk', 'https://example.com/translations/sk.json');
LOADRESOURCE('https://example.com/translations/');
```

### LOCALIZE(fn)

Type: `method`

Sets the delegate that returns the language of each request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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`.

Example: Language from the query or the header
```js
LOCALIZE(function(req, res) {
	var lang = req.query.language || (req.headers['accept-language'] || '').substring(0, 2);
	return lang === 'sk' ? 'sk' : 'en';
});
```

### LOCALIZE(url, [flags], [minify])

Type: `method`

Serves static files of a URL translated into the language of the request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL, for example `/docs/*.md`. |
| `flags` | `Array` | no | `[]` | File extensions (`.md`) and `nocompress`. |
| `minify` | `Boolean` | no | `true` | Minifies HTML. |

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.

Example: Localized Markdown
```js
LOCALIZE('/docs/*.md');
LOCALIZE('/templates/*.html', ['nocompress']);
```

### DEF.onLocale = function(req, res, isStaticFile)

Type: `delegate`

The delegate that returns the language of a request; `null` by default.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `req` | `Request` | yes |  | The request. |
| `res` | `Response` | no |  | The response. |
| `isStaticFile` | `Boolean` | no |  | `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.

Example: Language of the user
```js
DEF.onLocale = function(req) {
	return req.user ? req.user.language : 'en';
};
```

### AUTH({ locale: function(user, req) })

Type: `config` · Since: `0.0.57`

Option of the built-in session `AUTH()` that sets the language from the user.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `user` | `Object` | yes |  | The user data from `onread`, or `null`. |
| `req` | `Request` | yes |  | 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`.

Example: Language from the user
```js
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';
	}
});
```

### controller.language

Type: `property`

The language of the controller; views and e-mails use it.

Returns: `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.

Example: Language from the URL
```js
exports.install = function() {
	ROUTE('GET /{lang}/', home);
};

function home(lang) {
	this.language = lang;
	this.view('index');
}
```

### req.language

Type: `property`

The language of the request.

Returns: `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.

Example: Read the language
```js
function detail() {
	var lang = this.req.language;
	this.plain(lang);
}
```

### req.localize()

Type: `method`

Runs `DEF.onLocale` again and returns the new language.

Returns: `String` The language.

Useful when something that the delegate reads (a cookie, the user) has changed during the request.

Example: Refresh the language
```js
function setlanguage() {
	this.req.user.language = this.query.lang;
	this.language = this.req.localize();
	this.redirect('/');
}
```

### $.language

Type: `property`

The language of the request in schemas, operations, middleware and `AUTH()`.

Returns: `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.

Example: Use it in a schema
```js
schema.addWorkflow('send', function($) {
	var subject = TRANSLATE($.language, 'Your message was received');
	$.success(subject);
});
```

### @(Text)

Type: `method`

Marks text for translation in views and static HTML files.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `Text` | `String` | yes |  | 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.

Example: Translated text
```html
<h1>@(Products)</h1>
<button title="@(Add to cart)">@(Add)</button>
<p>@(#welcome)</p>
```

### @{resource([name], key)}

Type: `method`

Prints a value from a resource file in a view, HTML-encoded.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | `default` | The resource name. |
| `key` | `String` | yes |  | 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.

Example: Resource values
```html
<p>@{resource('welcome')}</p>
<p>@{resource(language, 'welcome')}</p>
```

### @{language}

Type: `property`

The language of the request inside a view.

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.

Example: The lang attribute
```html
<html lang="@{language}">
```

### @{notranslate}

Type: `method`

Turns off translation of `@(...)` in a view.

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.

Example: A view without translation
```html
@{notranslate}
<p>@(This text stays as it is)</p>
```

### MAIL(address, subject, view, [model], [language], [callback])

Type: `method`

Sends an e-mail rendered from a view, in a given language.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `address` | `String|Array` | yes |  | The recipient or recipients. |
| `subject` | `String` | yes |  | The subject. |
| `view` | `String` | yes |  | The view name. |
| `model` | `Object` | no |  | The model of the view. |
| `language` | `String` | no |  | The language. |
| `callback` | `Function` | no |  | `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.

Example: A translated e-mail
```js
MAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {
	err && console.log(err);
});
```

### HTMLMAIL(address, subject, body, [language], [callback])

Type: `method` · Since: `0.0.37`

Sends a raw HTML e-mail, translated into a given language.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `address` | `String|Array` | yes |  | The recipient or recipients. |
| `subject` | `String` | yes |  | The subject. |
| `body` | `String` | yes |  | The HTML body. |
| `language` | `String` | no |  | The language. |
| `callback` | `Function` | no |  | `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.

Example: A translated HTML e-mail
```js
HTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for signing up.)</p>', 'sk');
```

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

Type: `method`

Renders a view to a string, optionally in a given language.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The view name. |
| `model` | `Object` | no |  | The model. |
| `layout` | `String` | no |  | The layout. |
| `repository` | `Object` | no |  | The repository. |
| `language` | `String` | no |  | The language. |

Returns: `String` The HTML.

The language is used for `@(...)` in the view. Without it the view is translated with `default.resource`.

Example: Render in Slovak
```js
var html = VIEW('mails/invoice', invoice, '', null, 'sk');
```

### date.format([format], [resource])

Type: `method`

Formats a date; month and day names are read from a resource.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `format` | `String` | no |  | The format, for example `dddd d. MMMM yyyy`. |
| `resource` | `String` | no | `default` | The resource with names of months and days. |

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.

Example: Localized names
```js
// sk.resource: January : január, Monday : pondelok
var text = NOW.format('dddd d. MMMM yyyy', 'sk');
```

### builder.resource(name, [prefix])

Type: `method`

Sets the resource and the key prefix for error messages.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The resource name. |
| `prefix` | `String` | no | `''` | A prefix for keys. |

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.

Example: Errors from a resource
```js
var builder = new ErrorBuilder();
builder.resource('sk', 'error-');
builder.push('email'); // reads error-email from sk.resource
```

### builder.setResource(name)

Type: `method`

Sets only the resource for error messages.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: Fixed language
```js
var builder = new ErrorBuilder();
builder.setResource('de');
```

### builder.setPrefix(prefix)

Type: `method`

Sets the prefix of keys for error messages.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `prefix` | `String` | yes |  | The prefix. |

Returns: `ErrorBuilder` The builder.

An error pushed with a name is read as `prefix + name` from the resource.

Example: A prefix
```js
var builder = new ErrorBuilder();
builder.setPrefix('error-');
builder.push('name');
```

### schema.setResource(name)

Type: `method`

Reads the errors of a schema from a fixed resource.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The resource name. |

Returns: `SchemaBuilderEntity` The schema.

Without it, errors of the schema are translated with the language of the request.

Example: Errors from errors.resource
```js
NEWSCHEMA('Contact', function(schema) {
	schema.setResource('errors');
	schema.define('email', 'Email', true);
});
```

### schema.setPrefix(prefix)

Type: `method`

Sets a prefix for resource keys of the schema errors.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `prefix` | `String` | yes |  | The prefix. |

Returns: `SchemaBuilderEntity` The schema.

A required or invalid field `email` is read as `prefix + 'email'` from the resource.

Example: Prefixed keys
```js
NEWSCHEMA('Contact', function(schema) {
	schema.setPrefix('contact-');
	schema.define('email', 'Email', true); // key: contact-email
});
```

### F.register(path)

Type: `method`

Adds a `.resource` file from another location to a resource.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | 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.

Example: Resources of a module
```js
F.register(PATH.root('modules/shop/sk.resource'));
```

### F.resources

Type: `property`

The cache of parsed resources, by name.

Returns: `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.

Example: Clear the cache
```js
F.resources = {};
```

### PATH.resources([filename])

Type: `method`

Returns the path of the resources directory or of a file in it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` The absolute path.

Example: Path to a resource
```js
var filename = PATH.resources('sk.resource');
```

### directory_resources : /resources/

Type: `config`

The directory with resource files.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `directory_resources` | `String` | no | `/resources/` | A path relative to the root of the application. |

Example: Another directory
```text
directory_resources     : /translations/
```

### allow_localize : true

Type: `config`

Translates `.html` and `.htm` files from `public/` with `@(...)`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `allow_localize` | `Boolean` | no | `true` | Enables translation of static HTML files. |

The translated files are cached for each language in release mode.

Example: Turn it off
```text
allow_localize          : false
```

### default_interval_clear_resources : 20

Type: `config`

How often, in minutes, the cache of resources is cleared.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `default_interval_clear_resources` | `Number` | no | `20` | Minutes. |

After clearing, resource files are read again on the next use, so changes appear without a restart. The `clear` event is emitted with `resources`.

Example: Every five minutes
```text
default_interval_clear_resources : 5
```

### default_errorbuilder_resource_name : name

Type: `config`

The default resource of every new `ErrorBuilder`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `default_errorbuilder_resource_name` | `String` | no |  | The resource name. |

Not set by default. The framework still switches error builders to the language of the request before it sends them.

Example: Errors from errors.resource
```text
default_errorbuilder_resource_name : errors
```

### default_errorbuilder_resource_prefix : prefix

Type: `config`

The default key prefix of every new `ErrorBuilder`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `default_errorbuilder_resource_prefix` | `String` | no | `''` | The prefix. |

Not set by default (an empty prefix).

Example: Prefixed keys
```text
default_errorbuilder_resource_prefix : error-
```

### total4 translate [path | "text" | filename]

Type: `method`

Creates `translate.resource` with every text to translate.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `argument` | `String` | no |  | 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.

Example: Create the file
```bash
total4 translate
total4 translate "Add to cart"
```

### total4 translatecsv

Type: `method`

Writes the texts to translate into `translate.csv`.

The CSV has the columns `Hash;Text;Translation`. Fill the last column, then convert it back with `total4 csv`.

Example: Export to CSV
```bash
total4 translatecsv
```

### total4 csv <filename>

Type: `method`

Creates a resource file from a CSV file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | 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`.

Example: Import from CSV
```bash
total4 csv sk.csv
```

### total4 diff <source> <target>

Type: `method`

Lists keys to add to and to remove from a resource.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `String` | yes |  | The new file, for example `translate.resource`. |
| `target` | `String` | yes |  | 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.

Example: Find new texts
```bash
total4 diff translate.resource resources/sk.resource
```

### total4 merge <source> <target>

Type: `method`

Copies values from one resource into another.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `String` | yes |  | The file with new values. |
| `target` | `String` | yes |  | 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.

Example: Merge translations
```bash
total4 merge translated.resource resources/sk.resource
```

### total4 clean <source>

Type: `method`

Aligns the keys and values of a resource file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `String` | yes |  | The resource file. |

Writes `<source>-cleaned.txt` with all keys padded to the same width and ` : ` between key and value.

Example: Clean a file
```bash
total4 clean resources/sk.resource
```
