Transloco Goes Functional: A Guide to Transloco's Functional Transpiler
Last updated
Was this helpful?
Last updated
Was this helpful?
Written by Shahar Kazaz, Co-Creator & maintainer of Transloco
A friend of mine shared an exciting use-case: he needed to change translation values depending on whether the user had access to a specific feature. As the translations were scattered across the app, dynamically replacing many of them became quite a hassle.
That got me thinking about solving this problem globally โ and then the idea hit me: why not allow function calls directly in the translation values?
The Transloco transpiler is responsible for resolving translation values. For instance, when provided with Hello {{ key }}
, the transpiler replaces the dynamic variable key
based on the provided parameters or, in some cases, the translation object itself.
Now, in addition to the default transpiler, Transloco offers the new FunctionalTranspiler. This allows you to embed function calls within your translation values, enabling a new level of flexibility. You can now leverage the power of Angularโs Dependency Injection (DI) and make your translations even more dynamic.
The FunctionalTranspiler is fully compatible with the default TranslocoTranspiler. This means you can switch to the functional version without worrying about breaking existing translations.
Switching back to the default transpiler will require removing any functional syntax from your translations.
To start using the Functional Transpiler, you need to add the following provider in your app's providers:
To use functions within your translations, you first need to define them for the transpiler. You do this by creating a class that implements the TranslocoTranspilerFunction interface.
For example, letโs say we want to display different text based on whether the user is allowed to access a specific feature:
In this case, our transpile function accepts three arguments:
The name of the feature flag.
The value to show when the feature is enabled.
The value to show when the feature is disabled.
You can inject and use this custom transpiler function like this:
Now, to use this function in a template, you just need to call it as a regular function within your translation string:
In this example, the function checks whether the newDashboard feature flag is enabled. If it is, it will display "has flag"; otherwise, it will show "missing flag".
If the function returns a string with interpolation syntax (e.g., {{value}}
), the transpiler will replace it with the relevant params or references, just like the default transpiler.
If your functionโs parameter contains a comma, be sure to escape it properly (\\,
). For example, 'Hello {{user}}\\, welcome'
will pass "Hello {{user}}, welcome"
as the first parameter.
Transloco also gives you the flexibility to create your own custom transpilers. Have a cool idea for a transpiler? Implement it and share it with the community! ๐ค