Extending the preprocessor
If the built-in functions and filters are not enough, you can add your own template functions in JavaScript, for example for custom hashing or formatting.
Adding helpers
Put .js files into a _tera/ directory in your app:
text
my-app/
├── app.yml.jinja
├── metadata.yml
├── store-metadata.yml
└── _tera/
└── helpers.jsAll .js files in _tera/ are evaluated before a template of the app is rendered. They can register:
- Template functions with
registerTeraHandler(name, fn).fnreceives one object with the named arguments of the call and returns any JSON-compatible value, or a promise for one. - A postprocessor with
registerPostprocessor(fn).fnreceives the file name and the rendered output, and must return the final content as a string. Only one postprocessor can be registered.
js
// _tera/helpers.js
registerTeraHandler("first32", (args) => {
if (typeof args?.str !== "string") {
return "";
}
return args.str.slice(0, 32);
});
registerPostprocessor((fileName, content) => {
return content.trimEnd() + "\n";
});yaml
# app.yml.jinja
environment:
SHORT_KEY: "{{ first32(str=derive_entropy(identifier='key')) }}"Runtime
Helpers run in Boa, a JavaScript engine embedded in n5i, without file system or network access. The built-in objects of the language are available, plus:
console.log,console.warn,console.error, which write to n5i's logscrypto.getRandomValues()andcrypto.randomUUID()TextEncoderandTextDecoderURLsetTimeoutandstructuredClone
import is not supported, so bundle any libraries into the file. Each call must finish within 2 seconds.
Random values differ on every render. For values that must stay the same, such as passwords, use derive_entropy.