0.5.0 • Published 1 year ago

popu v0.5.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

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 handled
  • data: initial data object
  • key: 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 of VAR
  • Default value

    • ${VAR:-default} -> value of VAR if set and non-empty, otherwise default
    • ${VAR:=default} -> value of VAR if set and non-empty, otherwise default and set VAR to default
  • Required value

    • ${VAR:?error} -> value of VAR if set and non-empty, otherwise exit with error
  • Alternative value

    • ${VAR:+replacement} -> replacement if VAR is set and non-empty, otherwise empty
  • Length of value

    • ${VAR:#} -> length of value of VAR if set and non-empty, otherwise 0

more usage examples

Credits

0.5.0

1 year ago

0.4.0

1 year ago

0.3.0

1 year ago

0.2.2

1 year ago

0.2.1

1 year ago

0.2.0

1 year ago

0.1.3

1 year ago

0.1.2

1 year ago

0.1.1

1 year ago