ez-string
A string template renderer for JavaScript without memory leaks. It supports referencing variables by position, by name. One can access properties and array elements.
API reference
Example
const render = require('ez-string').render;
let book;
book = render('One of my favorite books is "{0}" by {1}.', 'The Name of the Wind', 'Patrick Rothfuss');
book = render('One of my favorite books is "{title}" by {author}.',
{ title: 'The Name of the Wind', author: 'Patrick Rothfuss'});
let example;
example = render('{{title}}');
book = render('"{arr[0]}" was first published in {arr[1]}.',
{ arr: ['The Hobbit', 1937]});
book = render('"{book.title}" was written by {book.author["first name"]} {book.author["last name"]}. It was published in {book.year}.', {
book: {
title: 'Marina',
year : 1999,
author: {
'first name': 'Carlos',
'last name': 'Zafon'
}
}
});
example = render('{data["\\\\"]}', {
data: {'\\': 'backslash'}
});
example = render('{data["\\""]}', {
data: {'"': 'quote'}
});
Installation
Using NodeJS:
$ npm i --save ez-string
const render = require('ez-string').render;
let book;
book = render('One of the best books by {author} is "{title}".', {
author: 'Stephen King',
title: '11/22/63'
});
In a browser:
<script src="ez-string.js"></script>
<script>
let book;
book = render('One of the best books by {author} is "{title}".', {
author: 'Stephen King',
title: '11/22/63'
});
</script>
Why ez-string
The most important reason is that this library doesn't leak memory.
Many of the existing template renderers perform a two-step process. They compile a string template into a JavaScript function and then execute it while passing context data. However, most users of such libraries rarely cache the resulting compiled function. Instead they may compile the same template again and again. Due to inticacies of NodeJS memory garbage collection. Such pattern usually results in a memory leak, as described by Meteor developers.
Library documentation is here.