https://github.com/mitranim/statil
Simple string templating with embedded JS
https://github.com/mitranim/statil
Last synced: 11 months ago
JSON representation
Simple string templating with embedded JS
- Host: GitHub
- URL: https://github.com/mitranim/statil
- Owner: mitranim
- Created: 2015-02-25T17:17:45.000Z (almost 11 years ago)
- Default Branch: master
- Last Pushed: 2018-12-17T11:45:12.000Z (about 7 years ago)
- Last Synced: 2025-02-24T06:44:39.857Z (11 months ago)
- Language: JavaScript
- Homepage:
- Size: 139 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
## 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](https://github.com/mitranim/papyre).
## Why
Simple templating. Extremely flexible. Extremely lightweight.
Alternatives tend to involve monstrously large dependencies like Lodash.
## Usage
Short form:
```js
const {compileTemplate} = require('statil')
compileTemplate(`Hello {{$.name}}!`)({name: 'world'})
// 'Hello world!'
```
Long form:
```js
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 >>`:
```js
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