popu
v0.5.0
Published
Object populate/template tools
Downloads
25
Maintainers
Readme
popu
Object populate/template tools
Usage: template
The string submodule is a very simple mustache like variable replacement with no special features:
import {template} from 'popu';
template('${xfoo} ${say.what}', {xfoo: 'yep', say: {what: 'yep'}});
// yep yep
Usage: renderObject
The much more interesting part of this module is the object sub-module which does a deep clone and runs strings through template (including keys!)
config.json:
{
"magic_key_${magic}": {
"key": "interpolation is nice ${value}"
}
}
import {renderObject} from 'popu';
renderObject(require('./template.json'), {magic: 'key', value: 'value'});
result:
{
"magic_key_key": {
"key": "interpolation is nice value"
}
}
Custom render
You can override default renderer using the third argument in object
(template
is default):
template.json:
{
"magic": {
"key": "interpolation is nice ${value}"
}
}
import popu from 'popu';
popu(require('./template.json'), {magic: 'key', value: 'value'}, (value, data, key) => {
return value;
});
result:
{
"magic": {
"key": "interpolation is nice ${value}"
}
}
key reference
Handler function gets three arguments:
value
: value which is about to be handleddata
: initial data objectkey
: key corresponding to the value
Using this data some complex logic could be implemented, for instance:
import popu, {template} from 'popu';
popu(require('./template.json'), {magic: 'key', value: 'value'}, (value, data, key) => {
// custom renderer for some special value
if (key === 'specialKey') {
return 'foo';
}
// usual string renderer
return template(value, data);
});
result:
{
"magic": {
"specialKey": "foo",
"key": "interpolation is nice value"
}
}
Parameter Expansion
popu
supports parameter expansion in view like environment files. Parameter expansion is applied for unquoted and
double-quoted values. Both braced (${VAR}) and unbraced ($VAR) expressions are supported.
For braced expressions, the following formats are supported:
Direct substitution
${VAR}
-> value ofVAR
Default value
${VAR:-default}
-> value ofVAR
if set and non-empty, otherwisedefault
${VAR:=default}
-> value ofVAR
if set and non-empty, otherwisedefault
and setVAR
todefault
Required value
${VAR:?error}
-> value ofVAR
if set and non-empty, otherwise exit with error
Alternative value
${VAR:+replacement}
->replacement
ifVAR
is set and non-empty, otherwise empty
Length of value
${VAR:#}
-> length of value ofVAR
if set and non-empty, otherwise 0
Credits
- json-templater for the idea
- var-expansion for the string renderer