An open API service indexing awesome lists of open source software.

https://github.com/brikcss/tplit

A simple, small, fast, all-purpose templating engine using the power and flexibility of native JavaScript template literals.
https://github.com/brikcss/tplit

Last synced: about 1 year ago
JSON representation

A simple, small, fast, all-purpose templating engine using the power and flexibility of native JavaScript template literals.

Awesome Lists containing this project

README

          

# Tplit

A simple, small, fast, all-purpose templating engine using the power and flexibility of native JavaScript template literals.



NPM version

NPM downloads per month

Travis branch

NPM version

Coverage Status

JavaScript Style Guide

code style: prettier

semantic release

Commitizen friendly

License

---

## Environment and browser support

| Node | ES Module | Browser | UMD | CLI |
| :--: | :-------: | :-----: | :-: | :-: |
| ✓ | ✓ | x | ✓ | x |

## Install

```sh
npm i -D @brikcss/tplit
```

## Usage

There are two ways to use tplit, each has their pros and cons:

1. Pass a string with `tplit()`:

_Pros_: Most flexible, most configuration options.

_Cons_: Can not use outside scope / context (though you can pass your own context data object).

_Syntax_:

```js
tplit((template = ""), (options = {}))((context = {}));
```

_Example_:

```js
import tplit from "@brikcss/tplit";
const compiled = tplit("Hello ${this.name}")({ name: "World" });
const compiledWithOptions = tplit("Hello ${this.name}", {
prop: "props",
map: value => value.toUpperCase()
})({ name: "World" });
// console.log(compiled) => 'Hello World'
// console.log(compiledWithOptions) => 'Hello WORLD'
```

2. Call with template literal function with `tplitReduce()`:

_Pros_: Can use outside scope / context.

_Cons_: Fewer configuration options.

_Syntax_:

```js
tplitReduce((map = arg => arg))`My template string`;
```

_Example_:

```js
import { tplitReduce } from "@brikcss/tplit";
const name = "World";
const compiled = tplitReduce(
(map = arg => arg.toUpperCase())
)`Hello ${name}`;
// console.log(compiled) => 'Hello WORLD'
```

## Options

- `prop` {`String`} (`this`): Property to use for context Object. _Note: Not available with default `tplit()` method._
- `split` {`Boolean`} (`false`): Set true to split the template and return an Array of `[chunks, ...values]`. This would allow you to pass to other functions and further manipulate the template as desired. _Note: Not available with default `tplit()` method._
- `map` {`Function`} (`(value, key, context) => value`): Function to manipulate template values. This would allow you to, for example, sanitize HTML or otherwise manipulate context values.

## Examples

For more examples, see the [tests](./src/tplit.test.js).