The Transpiler
A deep dive into one of Transloco's main components, the transpiler.
toThe transpiler is responsible for resolving dynamic values in translations. For example, when given Hello {{ key }}
, the default transpiler will replace the dynamic variable key
with the corresponding value from the provided parameters or the translation object.
DefaultTranspiler
The default transpiler can be customized with different interpolation start and end markers to match your message parameters.
To configure the DefaultTranspiler
's interpolation markers, you need to provide a Transloco
configuration with the interpolation
property set.
Functional Transpiler
In addition to the default transpiler, Transloco also offers the FunctionalTranspiler
, which allows you to integrate function calls into your translation values. This makes your translations more dynamic by leveraging Angular's Dependency Injection system.
The FunctionalTranspiler
is compatible with the DefaultTranspiler
, meaning you can switch between them without breaking existing translations.
Switching back to the default transpiler will require removing any functional syntax from your translations.
Usage
To use a function in a translation, you need to provide it to the transpiler by creating a class that implements the TranslocoTranspilerFunction
interface.
For example, letโs say you want to display different texts based on whether the user has access to a specific feature:
In this case, the transpile
function accepts three arguments:
The feature flag's name.
The value to display if the user has the flag.
The value to display if the user does not have the flag.
Now, you can use the function in your translation files with the functional syntax:
In this case, the translation checks if the user has the newDashboards
feature flag. If they do, it displays "has flag"; otherwise, it displays "missing flag".
Usage Notes
If the function returns a string that contains interpolation syntax (e.g.,
{{ value }}
), the transpiler will replace it with the appropriate params or key references, just like the default transpiler.If your function parameters need to include a comma, escape it using
\\,
:
In this case, "Hello {{user}}, welcome"
will be the first parameter passed to the function.
Custom Transpiler
You can also provide a custom transpiler by creating a class that implements the TranslocoTranspiler
interface:
Last updated