1.0.4 โ€ข Published 3 years ago

terpolate v1.0.4

Weekly downloads
-
License
-
Repository
-
Last release
3 years ago

Terpolate

String interpolation for React, Preact, and plain DOM.

Why use Terpolate?

  • ๐Ÿ”ฌ Small: 0.3kb gzipped before factoring in React or Preact, or 0.5kb for the standalone DOM package.
  • ๐Ÿ”’ Safe: Builds an element tree using only string content, never dangerous HTML.
  • ๐Ÿ“Ÿ Compatible: Still supports outdated browsers such as Internet Explorer.

What are some use-cases?

  • ๐ŸŒ Internationalization (i18n)
  • ๐Ÿงผ Simple HTML sanitization

Installation

Install via NPM:

npm install terpolate

Usage

The package exports a single function, interpolate:

import { interpolate } from 'terpolate';

The function accepts two arguments:

  1. A string with markup to replace
  2. An object with markup tag component implementations

The return value is an element which can be included in the rendered value of your component.

For example:

function Blink({ children }) {
	return <span class="blink">{children}</span>;
}

function Message() {
	const interpolated = interpolate('Hello <Blink>world</Blink>', { Blink });
	// โ‡’ ['Hello ', <span class="blink">world</span>]

	return <div>{interpolated}</div>;
}

Handlers can be given as a string, component class or function, or as an element. When given as an element, the element is cloned with text inserted as children.

interpolate(
	'<strong>If you need help</strong>, visit our <a><HelpCenterIcon /> Help Center</a>.',
	{
		strong: 'strong',
		HelpCenterIcon,
		a: <a href="/help" />,
	}
);

Preact

All of the above still applies, but you should import from terpolate/preact instead:

import { interpolate } from 'terpolate/preact';

DOM

Similarly, import from terpolate/dom:

import { interpolate } from 'terpolate/dom';

The return value is a DocumentFragment which you can then append to a container:

const link = document.createElement('a');
link.href = '/help';
const element = interpolate(
	'<strong>If you need help</strong>, visit our <a>Help Center</a>.',
	{
		strong: 'strong',
		a: link,
	}
);
document.body.appendChild(element);

Note that the DOM entrypoint assumes a DOM is present, meaning it should be run either in a browser or in a Node.js environment with a DOM global using a module like jsdom.

License

Copyright 2021 Andrew Duthie

Released under the MIT License.

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago