Parse localization files and pass key-value map to templates, to dynamically render localized templates.


Keywords
language, localization, template, toml
License
ISC
Install
npm install langapply@0.2.2

Documentation

LangApply

A library to create lang objects from locale files (and even to render templates with such values).

How does it work

It reads .toml files from a specified folder and with given options (preCaching, caching, default locale to use, ...).

Then it can load the right localized properties for a given URL and Accept-Locale HTTP Header.

For example, if configured to feed from ./lang folder, when asked to load for url /subpage and with locales it, de;q=0.7, fr;q=0.6 it will try to load the file ./lang/subpage/it.toml and pass it to the given callback. Otherwise it will read ./lang/subpage/<X>.toml (where <X> is the configured default locale) and do the same. When a locale file is missing a key, the one from the default locale is used. Use these two files as an example:

  • it.toml
    hello = "Ciao"
  • en.toml (the example Default Locale)
    hello = "Hello"
    world = "World"

If it.toml is needed, the missing key will be loaded from en.toml. The provided callback will be passed the object

{
    hello: 'Ciao',
    world: 'World'
}

Usage

Initializing

It can be initialized like this.

    const langapply = require('langapply');

    /* ... */

    langapply.initialize(); // With default options

Rendering templates

It is meant to be used with Express and it allows to render templates.

You can render them like this.

    // inside your request handler
    langapply.render(
        request,
        response,
        template, // Filename of your template
        context, // The context, context.lang = {/*key-value*/} is inserted
        callback // The callback to be passed to response.render()
    );

It adds a lang field to your context and calls response.render(). You can access the values with something like {{ lang.yourkey }} in case you are using Handlebars templates.