Simple string templating with embedded JS
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.eslintrc
.gitignore
.npmignore
build.js
package.json
readme.md
yarn.lock

readme.md

Description

Templating function, very similar to lodash/template. Embeds JavaScript into templates.

Lightweight: < 100 lines of code, dependency-free.

Differences from lodash/template:

  • doesn't carry the entire Lodash with it
  • always strict mode
  • no with, no implicit globals, no imports
  • better default delimiters: {{ expression }} and << statement >>
  • no special escape delimiter, escape manually
  • better option naming
  • slightly more readable compiled code

Statil is intended for templates that embed JS. For the opposite, when you want to write templates primarily in JavaScript, using JSX, see the spiritually related library Papyre.

Why

Simple templating. Extremely flexible. Extremely lightweight.

Alternatives tend to involve monstrously large dependencies like Lodash.

Usage

Short form:

const {compileTemplate} = require('statil')

compileTemplate(`Hello {{$.name}}!`)({name: 'world'})
// 'Hello world!'

Long form:

const {compileTemplate} = require('statil')

const templateStr = `Hello {{$.name}}!`

// Optional settings
const options = void {
  reExpression: /{{\s*([\s\S]+?)\s*}}/g,
  reStatement: /<<\s*([\s\S]+?)\s*>>/g,
  contextName: '$',
}

const template = compileTemplate(templateStr, options)

template({name: 'world'})
// 'Hello world!'

For control flow, use << statements >>:

const templateStr = `
<< for (const name of $.names) { >> {{name}} << } >>
`

compileTemplate(templateStr)({names: ['one', 'two', 'three']})
//  one  two  three

Misc

I'm receptive to suggestions. If this library almost satisfies you but needs changes, open an issue or chat me up. Contacts: https://mitranim.com/#contacts