@matchlighter/nodal_i18n
v0.2.0
Published
An fast I18n library with advanced interpolation and inheritance capabilities.
Downloads
2
Readme
@matchlighter/nodal_i18n
An fast I18n library with advanced interpolation and inheritance capabilities.
Language Files
Language data is expressed as a plain Javascript object, and can thus be transmitted to your frontend via JSON or can be imported from JSON or YAML files using tools such as Webpack. Documentation of the language file format will primarily be written in YAML for its conciseness and better human-readability vs JSON.
Example Language file:
title: Simple Application
base_tab:
tooltip: $t(`${path[0:-1]}.title`)
header_tabs:
home:
title: Home
# A basic entry that includes and interpolation. This example will resolve to "Return to "Simple Application" Home page"
tooltip: Return to "$t(`title`)" Home page
about:
title: About Us
# '.' separated object notation is also understood and interpreted the same as the above notation:
pricing.title: Pricing
# A `$base` key indicates an object that any other keys in the parent object (in this case `header_tabs`) should extend from.
$base:
# The overall effect of this example is that, for any tabs that do not contain a `tooltip` key, `header_tabs.$base.tooltip` will be returned.
# In this example, however, `header_tabs.$base.tooltip` also implements an interpolation.
# Thus `header_tabs.about.tooltip` is ultimately resolved to `header_tabs.about.title` or "About Us".
tooltip: $t(`header_tabs.${path[1]}.title`)
# The `$base` tag can also implement an interpolation, thus the following (given the definition of base_tab) would result in the same effect:
$base: $t(`base_tab`)
# This can also be achieved per-key using the `$extends` tag:
contact:
$extends: $t(`base_tab`)
# ... Which may also be expressed as a list:
$extends:
- $t(`base_tab`)
title: Contact Us
# A `$missing` key can be provided and will be the default value if an _immediate_ subkey is missing.
# Note that a present `$missing` will automatically inherit from `$base` as normal nodes do, but will only do so if `$missing` is actually specified.
$missing:
title: $path[-2]
# To use `$base` for a non-present `$missing`, the following can be used:
$missing: $base
Interpolations
The interpolations syntax implements a small-but-powerful Domain-Specific-Language that can make your language files quite dynamic.
Values in the language file/data are interpreted as plain strings until a $
character is encountered.
Examples:
- Simple Interpolation
# -- Language YAML: hello.planet: Hello $planet
// -- Queries: t('hello.planet', { planet: 'Earth' }) //-> "Hello Earth" t('hello.planet', { planet: 'Mars' }) //-> "Hello Mars"
- Lookup Interpolation
# -- Language YAML: planets: mars: Mars pluto: Pluto (Not Actually a Planet) hello: planet: Hello $t(`planets.$planet`)
// -- Queries: t('hello.planet', { planet: 'mars' }) //-> "Hello Mars" t('hello.planet', { planet: 'pluto' }) //-> "Hello Pluto (Not Actually a Planet)"