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.
Simple templating. Extremely flexible. Extremely lightweight.
Alternatives tend to involve monstrously large dependencies like Lodash.
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 {
expressionRegexp: /{{\s*([\s\S]+?)\s*}}/g,
statementRegexp: /<<\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
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