@philiprehberger/template
v0.1.2
Published
Lightweight string template engine with safe interpolation, conditionals, and loops
Downloads
322
Readme
@philiprehberger/template
Lightweight string template engine with safe interpolation, conditionals, and loops.
Installation
npm install @philiprehberger/templateUsage
Basic interpolation
import { template } from '@philiprehberger/template';
template('Hello {{name}}!', { name: 'World' });
// => "Hello World!"Dot notation
import { template } from '@philiprehberger/template';
template('Hello {{user.name}}', { user: { name: 'Alice' } });
// => "Hello Alice"Conditionals
import { template } from '@philiprehberger/template';
template('{{#if premium}}Welcome back!{{/if}}', { premium: true });
// => "Welcome back!"
template('{{#unless loggedIn}}Please sign in.{{/unless}}', { loggedIn: false });
// => "Please sign in."Loops
import { template } from '@philiprehberger/template';
template('{{#each items}}{{this}}, {{/each}}', { items: ['a', 'b', 'c'] });
// => "a, b, c, "Filters
import { template } from '@philiprehberger/template';
template('{{name | upper}}', { name: 'hello' }, {
filters: { upper: (s) => s.toUpperCase() },
});
// => "HELLO"Raw output
import { template } from '@philiprehberger/template';
template('{{{html}}}', { html: '<b>bold</b>' });
// => "<b>bold</b>"Compile
import { compile } from '@philiprehberger/template';
const render = compile('Hello {{name}}');
render({ name: 'Alice' }); // => "Hello Alice"
render({ name: 'Bob' }); // => "Hello Bob"API
template(tmpl, data, options?)
Renders a template string with the given data.
| Parameter | Type | Description |
| --------- | ---- | ----------- |
| tmpl | string | Template string with {{expressions}} |
| data | Record<string, unknown> | Data object for interpolation |
| options | TemplateOptions | Optional configuration |
Returns string.
compile(tmpl, options?)
Pre-compiles a template for repeated rendering.
| Parameter | Type | Description |
| --------- | ---- | ----------- |
| tmpl | string | Template string with {{expressions}} |
| options | TemplateOptions | Optional configuration |
Returns (data: Record<string, unknown>) => string.
TemplateOptions
| Property | Type | Default | Description |
| -------- | ---- | ------- | ----------- |
| escape | boolean | true | HTML-escape interpolated values |
| filters | Record<string, (value: string) => string> | {} | Named filter functions for pipe syntax |
Development
npm install
npm run build
npm testSupport
If you find this project useful:
