JavaScript Custom Helpers
Custom helpers allow you to extend the engine to suit your specific application needs.
To make your helpers can be run in our system, you have to follow this function signature when implementing them:
functionName.js
function functionName(context, options) {
// ...
}
where:
context: first input parameteroptions: an object give you access to paramters, hash arguments
Inside options object, you can access to two properties:
params: an object contains all params except the first one. (The first param is thecontext)hash: a key-value collection allows user access the input parameters
The name of a file must be exactly the same with the name of the function.
Usage:
Example:
Assume we have data like below:
{
"items": [
{
"key": "color",
"label": "green",
"content": "001"
},
{
"key": "url",
"content": "www.example.com"
},
{
"key": "version",
"content": "1.0.0"
}
]
}
We want a helper that can find item base on key property and then return value of required property (content or label).
So we need to implement a helper which will receive 3 params:
- data: the input data
- key: value of
keyproperty of the item we want to extract - propertyName: the name of property in the item we want to get its value
Here is the implementation of the helper file that uses options.params to access paramters
getItemValue.js
function getItemValue(context, options) {
const inputData = context;
const params = options.params || [];
const key = params[0];
const propertyName = params[1];
// Check valid paramenters
if (!Array.isArray(inputData) || inputData.length === 0) return '';
if (key === null || key === '') return '';
if (propertyName === null || propertyName === '') return '';
// Find expected item
const found = inputData.find((x) => x && x.key === key);
if (found) {
return found[propertyName] ?? '';
}
return '';
}
Usage:
If you want to use options.hash, the implement should be like this:
function getItemValue(context, options) {
const inputData = context;
const key = options.hash('key', 'defaultValue');
const propertyName = options.hash('propertyName', 'defaultValue');
// Check valid paramenters
if (!Array.isArray(inputData) || inputData.length === 0) return '';
if (key === null || key === '') return '';
if (propertyName === null || propertyName === '') return '';
// Find expected item
const found = inputData.find((x) => x && x.key === key);
if (found) {
return found[propertyName] ?? '';
}
return '';
}
and when using the helper, you have to explicitly use the parameter name when pass value
HTML output:
<div>
<p>green - 001</p>
<a href="www.example.com">Website</a>
<p>Version: 1.0.0</p>
</div>