@nlib/template-string

Creates a string generator

Stats

StarsIssuesVersionUpdatedCreatedSize
@nlib/template-string
001.3.04 years ago4 years agoMinified + gzip package size for @nlib/template-string in KB

Readme

@nlib/template-string

Build Status Build status codecov dependencies Status devDependencies Status

Creates a string generator.

Install

npm install @nlib/template-string
const TemplateString = require('@nlib/template-string');

Usage

// Creates a generator
// Strings between [ and ] are recognized as keys.
const generate = new TemplateString('Hello [name1] and [name2]!');

const context1 = {name1: 'foo', name2: 'bar'};
console.log(generate(context1));
// Hello foo and bar!
const context2 = {name1: 'abc', name2: 'def'};
console.log(generate(context2));
// Hello abc and def!

// If a value is a function, it called with the context object
const context3 = {
  name1() {
    return 'pqr';
  },
  name2(context) {
    return `${context.name1}-stu`;
  }
};
console.log(generate(context3));
// Hello pqr and pqr-stu!

You can use custom marks.

const string = new TemplateString('Hello <value>name</value>!', {
  open: '<value>',
  close: '</value>',
});
console.log(string({name: 'foo'}));
// Hello foo!
const string = new TemplateString('Hello $name$!', {
  open: '$',
  close: '$',
});
console.log(string({name: 'foo'}));
// Hello foo!

Javascript API

new TemplateString(template: String, baseContext: Object, parseOptions: Object) → fn(context: any) → String

  • template: A template string.

  • baseContext: is used when fn generates a string. See Usage section.

  • parseOptions: configures marks.

    • open: String. The default value is '['.
    • close: String. The default value is ']'.
    • escape: String. The default value is ''.
  • fn: A string generator.

  • context: See Usage section.

LICENSE

MIT

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.