Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
micromustache
Advanced tools
A faster and smaller subimplementation of the {{mustache}} template engine for JavaScript
This tool covers the most important use case: interpolation: replacing variable names with their values from an object.
If that's all you need, micromustache is a drop-in replacement for MustacheJS.
But wait, don't ES6 Template literals solve the same problem? Read FAQ at the end of this page.
Micromustache achieves faster speed and smaller size by dropping the following features from MustacheJS:
arrName.1
though)If you can live with this, read on...
Signature:
/**
* @param {string} template - the template containing one or
* more {{variableNames}}
* @param {Object} [view={}] - an optional object containing values for
* every variable names that is used in the template. If it's omitted,
* it'll be assumed an empty object.
* @param {GeneralValueFn} [generalValueFn] an optional function that will be
* called for every key to generate a value. If the result is undefined
* we'll proceed with the default value resolution algorithm.
* This function runs in the context of view.
* @returns {string} template where its variable names replaced with
* corresponding values. If a value is not found or is invalid, it will
* be assumed empty string ''. If the value is an object itself, it'll
* be stringified by JSON.
* In case of a JSON error the result will look like "{...}".
*/
micromustache.render(template, view, generalValueFn);
Alias: .to_html()
Renders a template with the provided key/values from the view object. Example:
var person = {
first: 'Michael',
last: 'Jackson'
};
micromustache.render('Search {{first}} {{ last }} popcorn!', person);
//output = "Search Michael Jackson popcorn!"
You can even access array elements and length
because they are all valid keys in the array object in javascript:
var fruits = [ "orange", "apple", "lemon" ];
micromustache.render("I like {{0}}, {{1}} and {{2}} ({{length}} fruits!)", fruits);
//output = "I like orange, apple and lemon (3 fruits!)"
Note: if a key is missing or null, it'll be treated as it contained a value of empty string (i.e. the {{variableName}} will be removed from the template).
You can easily reference deep object hierarchies:
var singer = {
first: 'Michael',
last: 'Jackson',
children: [
{
first: 'Paris-Michael',
middle: 'Katherine',
},
{
first: 'Prince',
middle: 'Michael',
prefix: 'II'
},
{
first: 'Michael',
middle: 'Joseph',
prefix: 'Jr.'
}
]
}
micromustache.render("{{first}} {{last}} had {{children.length}} children: {{children.0.first}}, {{children.1.first}} and {{children.2.first}}", singer);
//output = "Michael Jackson had 3 children: Paris-Michael, Prince and Michael"
As you can see micromustache doesn't have loops or any other fancy feature that MustacheJS offers.
micromustache is a bit more forgiving than MustacheJS. For example, if the view
is null
or undefined
, MustacheJS throws an exception but micromustache doesn't.
Another difference (which can handle complicated edge cases) is that you can use functions as values for more flexibility. micromustache will simply call the function with the variable name and use its return value for interpolation:
/**
* @callback ValueFn
* @param {string} key - variable name for the current scope.
* For hierarchical names like {{a.b.c}} the key can be 'a' or 'b' or 'c'
* @param {Object} currentScope - the current object that the variable is
* supposed to resolved from
* @param {string[]} path - useful for hierarchical objects.
* for example a variable name like {{a.b.c}} sets the
* path to ['a', 'b', 'c']
* @param {number} currentPointer - the array index to where in the path we are
* at the moment. This is usually path.length - 1
* @returns {string|number|boolean|Object} the value to be interpolated
*/
function toUpper (key, currentScope, path, currentPointer) {
// key is the variable name
// By the way: "this" inside the function refers to the current object
return key.toUpperCase();
}
micromustache.render('I bought a {{screaming}} {{dog}}!!!', {
screaming: toUpper,
dog: toUpper
});
//output = 'I bought a SCREAMING DOG!!!'
The function runs synchronously in the context of the view object (i.e. this
refers to the view object). A more complex example:
var viewObject = {
repository: {
url: valueFn
}
};
function valueFn (key, currentScope, path, pathIndex) {
// this = viewObject
// key = 'url'
// currentScope = viewObject.repository
// path = ['repository', 'url']
// pathIndex = 1
return 'http://github.com/userpixel/micromustache.git';
}
micromustache.render('micromustache is at {{repository.url}}', viewObject);
//output = 'micromustache is at http://github.com/userpixel/micromustache.git'
Function signature:
/**
* @param {string} template - same as the template parameter to .render()
* @returns {function} a function that accepts a view object and returns a
* rendered template string
*/
micromustache.compile(template);
You can compile the template and get a function that can be used multiple times:
var templateEngine = micromustache.compile('Search {{first}} {{ last }} popcorn!');
output = templateEngine(person);
//output = "Search Michael Jackson popcorn!"
output = templateEngine({first:'Albert',last:'Einstein'});
//output = "Search Albert Einstein popcorn!"
This function makes your code cleaner but for simplicity doesn't use any memoization technique behind the scenes.
Just another name for micromustache.render()
for compatibility with MustacheJS.
There are 4 ways to get the library:
npm:
npm install micromustache
bower install micromustache
CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/micromustache/3.0.4/micromustache.js"></script>
Download directly from browser directory
Clone this Git repo:
git clone https://github.com/userpixel/micromustache
We use Mocha/Chai for tests:
npm test
The browser module loading tests ( AMD and global ) need to be loaded in the browser.
Q. What about ES6 template literals (AKA "template strings")? Aren't they gonna deprecate this library?
A. The expressions in a string literal can't reference values from outside its scope. Therefore it is not possible to simply pass an object and resolve variables from its keys. The tagged template literals cover part of the functionality but they:
However, since when they are natively supported by the runtime, they have a great performance and if you learn to use the native way of doing things, you don't have to learn an ever-changing library, though their functionality is more limited than MustacheJS.
MIT
FAQs
A fast, minimal and secure template engine for JavaScript
The npm package micromustache receives a total of 28,735 weekly downloads. As such, micromustache popularity was classified as popular.
We found that micromustache demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.