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

# Localization

> Translate views, static files, errors and e-mails with resource files and a language for each request.

Total.js translates text with **resource files**. A resource file is a plain text file with `key : value` lines in the `resources/` directory. The name of the file is the name of a language: `resources/sk.resource` holds the Slovak texts, `resources/de.resource` the German ones. `resources/default.resource` is the fallback for every language.

You mark text in views with `@(Text)`, choose the language of each request in a delegate, and the framework does the rest: it translates views, static HTML files, error messages and e-mail subjects. The exact reference is in [Localization](../../reference/localization/).

## Resource files

```text
// resources/sk.resource
# Comments start with // or #

title                : Moja stránka
welcome              : Vitajte
error-email          : Zadajte platnú e-mailovú adresu
```

Rules of the format:

- One key and one value per line, separated by ` : `. Keep a space after the colon: the parser skips the first character after `:`.
- Lines that start with `//` or `#` are comments; empty lines are ignored.
- The value is one line. Leading and trailing spaces are removed.
- Keys made of `T` and a base-36 hash of the text are translations of `@(Text)`. You do not write them by hand: the `total4 translate` command creates them (see below).

`RESOURCE()` reads a value by its key:

```js
var title = RESOURCE('sk', 'title');  // "Moja stránka"
var name = RESOURCE('title');          // reads resources/default.resource
```

When a key is missing in `sk.resource`, the value from `default.resource` is used. When it is missing there too, the result is an empty string.

A resource with one name can come from several places. The framework joins them in this order, and a later line with the same key wins:

1. files registered with `F.register('/path/to/sk.resource')` (useful for packages and modules),
2. `tmp/sk.resource`, written by `LOADRESOURCE()`,
3. `resources/sk.resource`.

Parsed resources are cached in `F.resources`. The cache is cleared every 20 minutes (`default_interval_clear_resources`), so changed files are read again without a restart.

## Choosing the language of a request

The language is a string: the name of the resource file without the extension. You set it with `LOCALIZE()` and a function; the function becomes `DEF.onLocale`:

```js
// definitions/localization.js
LOCALIZE(function(req, res) {
	var lang = req.query.language || req.cookie('language') || (req.headers['accept-language'] || '').substring(0, 2);
	switch (lang) {
		case 'sk':
		case 'de':
			return lang;
	}
	return 'en';
});
```

The function is called once per request and must return the language. The framework calls it:

- for static files, with `true` as the third argument,
- for routes, after authorization, so `req.user` is already known when you use `AUTH()`,
- for WebSocket connections, with `req` only.

The returned value is stored in `req.$language`. From there it goes to `controller.language`, `client.language` in WebSockets and `$.language` in schemas, operations and middleware.

With the built-in session authorization of `AUTH()`, use the `locale` option to take the 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';
	}
});
```

## Translating views

Write the text of the default language inside `@(...)`:

```html
<h1>@(Products)</h1>
<button title="@(Add to cart)">@(Add)</button>
<p>@(#welcome)</p>
<p>@{resource(language, 'title')}</p>
<p>Language: @{language}</p>
```

- `@(Text)` is replaced with the translation from the resource of `controller.language`. The key is `T` plus a hash of the text. When there is no translation, the original text stays.
- `@(#key)` reads `key` from the resource directly.
- `@{resource([name], key)}` prints a resource value, HTML-encoded. In views, `language` holds the current language.
- When `@(...)` is inside quotes, quotes in the translation are escaped, so it is safe in attributes and in inline scripts.
- `@{notranslate}` (or `@{nolocalize}`) anywhere in a view turns translation off for that view.

Translation happens when the view is compiled, so a view is compiled once for each language. In release mode the compiled views are cached; in debug mode they are compiled again on every render.

When no file exists for the language (for example `fr.resource` is missing), `@(Text)` keeps the original text.

You can change the language for one response before you render the view:

```js
exports.install = function() {
	ROUTE('GET /{lang}/', home);
};

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

## Static files

With `allow_localize: true` (the default), `.html` and `.htm` files from `public/` are translated like views: `@(Text)` is replaced and the result is cached per language in release mode.

`LOCALIZE(url, [flags], [minify])` translates other files too:

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

## Translating in code

```js
TRANSLATE('sk', 'Add to cart');          // the translation of @(Add to cart), or the text
TRANSLATE('sk', '#welcome');              // the same as RESOURCE('sk', 'welcome')
TRANSLATOR('sk', '<b>@(Products)</b>');  // replaces every @(...) in a string
```

Dates use resources for the names of months and days. `new Date().format('dddd d. MMMM yyyy', 'sk')` reads `January`…`December` and `Sunday`…`Saturday` as keys from `sk.resource`.

## Error messages

Errors of schemas and operations are translated with the language of the request:

```js
// resources/en.resource
// error-email            : Please enter a valid e-mail address

NEWSCHEMA('Contact', function(schema) {
	schema.define('email', 'Email', true);
	schema.addWorkflow('send', function($) {
		if (!$.model.email.endsWith('.com')) {
			$.invalid('error-email');
			return;
		}
		$.success();
	});
});
```

- A short name without spaces, colons or commas (`error-email`) is a resource key.
- `@(Text)` is translated like in views: `$.invalid('@(The e-mail is taken)')`.
- Any other text is sent as it is.

Without a translation the message is `The field "name" is invalid`. Use `schema.setResource()` and `schema.setPrefix()` to read errors from a fixed resource or with a key prefix, and `ErrorBuilder.resource()` for your own `ErrorBuilder`.

## E-mails

`MAIL()` and `HTMLMAIL()` take a language. The subject is translated, and the view of `MAIL()` is rendered in that language:

```js
MAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {
	err && console.log(err);
});
```

`controller.mail()` uses the language of the controller.

## Loading translations at runtime

`LOADRESOURCE()` writes a resource into `tmp/` and clears its cache. You can pass an object, an array or a URL:

```js
LOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });
LOADRESOURCE('sk', 'https://example.com/translations/sk.json');
LOADRESOURCE('https://example.com/translations/');  // { sk: {...}, de: {...} }
```

## The translate tool

The `total4` command creates and maintains resource files. Run it in the root of the application:

| Command | What it does |
| --- | --- |
| `total4 translate` | Finds every `@(Text)` in `.html`, `.js` and sitemap files, and keys of `$.invalid('key')`, and writes `translate.resource` |
| `total4 translate "Text"` | Prints the key of one text |
| `total4 translate <file>` | Creates `translate.resource` from a text file, one text per line |
| `total4 translatecsv` | Writes the texts into `translate.csv` (`Hash;Text;Translation`) |
| `total4 csv <file.csv>` | Creates a resource from the first two columns of a CSV |
| `total4 diff <source> <target>` | Writes `<target>-diff.txt` with keys to add to and to remove from the target |
| `total4 merge <source> <target>` | Writes `<target>-merged.txt`: the target with values taken from the source |
| `total4 clean <source>` | Writes `<source>-cleaned.txt` with aligned keys |

A typical workflow: run `total4 translate`, copy `translate.resource` to `resources/sk.resource`, translate the values, and after the next change run `total4 diff translate.resource resources/sk.resource` to find new texts.
