micromustache
Advanced tools
Comparing version 2.2.3 to 3.0.0
{ | ||
"name": "micromustache", | ||
"version": "2.2.2", | ||
"version": "3.0.0", | ||
"homepage": "https://github.com/userpixel/micromustache", | ||
@@ -5,0 +5,0 @@ "description": "A faster and smaller subimplementation of the {{mustache}} template engine for JavaScript", |
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.micromustache = f()}})(function(){var define,module,exports;module={exports:(exports={})}; | ||
/** | ||
* Replaces every {{variable}} inside the template with values provided by view | ||
* If the value is a function, call it passing the name of the variable as the only argument. | ||
* @param template {string} the template containing one or more {{key}} | ||
* @param view {object} an object containing string (or number) values for every key that is used in the template | ||
* @return {string} template with its valid variable names replaced with corresponding values | ||
*/ | ||
function render (template, view) { | ||
* Replaces every {{variable}} inside the template with values provided by view | ||
* If the value is a function, call it passing the name of the variable as the only argument. | ||
* | ||
* @param template {string} the template containing one or more {{variableNames}} | ||
* @param [view={}] {object} an optional object containing values for every variable names | ||
* that is used in the template | ||
* @return {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 "{JSON_ERROR: ... }". | ||
*/ | ||
function render(template, view) { | ||
//don't touch the template if it is not a string | ||
if (typeof template !== 'string') { | ||
return template; | ||
return template; | ||
} | ||
//if view is not a valid object, assume it is an empty object which effectively removes all variable assignments | ||
//if view is not a valid object, assume it is an empty object | ||
//which effectively removes all variable interpolations | ||
if (typeof view !== 'object' || view === null) { | ||
view = {}; | ||
view = {}; | ||
} | ||
return template.replace(/\{?\{\{\s*(.*?)\s*\}\}\}?/g, function (match, varName) { | ||
var value = view[varName]; | ||
return template.replace(/\{\{\s*(.*?)\s*\}\}/g, function(match, varName) { | ||
var path = varName.split('.'); | ||
function resolve(currentScope, pathIndex) { | ||
if (currentScope === null) { | ||
return ''; | ||
} | ||
var key = path[pathIndex]; | ||
var value = currentScope[key]; | ||
switch (typeof value) { | ||
case 'string': | ||
case 'number': | ||
case 'boolean': | ||
return value; | ||
case 'function': | ||
//if the value is a function, call it passing the variable name | ||
return value(varName); | ||
default: | ||
//anything else will be replaced with an empty string. This includes object, array, date, regexp and null. | ||
return ''; | ||
case 'string': | ||
case 'number': | ||
case 'boolean': | ||
return value; | ||
case 'function': | ||
//if the value is a function, call it passing the variable name | ||
return value.call(view, key, currentScope, path, pathIndex); | ||
case 'object': | ||
if (value === null) { | ||
return ''; | ||
} | ||
pathIndex++; | ||
if ( pathIndex < path.length ) { | ||
return resolve(value, pathIndex); | ||
} else { | ||
try { | ||
return JSON.stringify(value); | ||
} catch (jsonError) { | ||
return '{...}'; | ||
} | ||
} | ||
default: | ||
//anything else will be replaced with an empty string (date, regexp, etc). | ||
return ''; | ||
} | ||
} | ||
return resolve(view, 0); | ||
}); | ||
@@ -36,18 +64,19 @@ } | ||
/** | ||
* This function really doesn't make things particularly faster. | ||
* However it makes the repeated calls shorter! | ||
* @param template {string} the template containing one or more {{key}} | ||
* @return {function} a function that calls render(template, view) under the hood | ||
* This function makes repeated calls shorter by returning a compiler function | ||
* for a particular template that accepts data and returnes the rendered string. | ||
* It doesn't make the code faster since the compiler still uses render internally. | ||
* | ||
* @param template {string} same as the template parameter to render() | ||
* @return compiler(view) {function} a function that accepts a view and returns a rendered template | ||
*/ | ||
function compile (template) { | ||
//create and return a function that will always apply this template under the hood | ||
return function (view) { | ||
return render(template, view); | ||
}; | ||
//create and return a function that will always apply this template under the hood | ||
return function compiler (view) { | ||
return render (template, view); | ||
}; | ||
} | ||
exports.render = render; | ||
exports.to_html = render; | ||
exports.compile =compile; | ||
exports.to_html = exports.render = render; | ||
exports.compile = compile; | ||
return module.exports;}); |
@@ -1,1 +0,1 @@ | ||
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.micromustache=f()}})(function(){var define,module,exports;module={exports:exports={}};function render(template,view){if(typeof template!=="string"){return template}if(typeof view!=="object"||view===null){view={}}return template.replace(/\{?\{\{\s*(.*?)\s*\}\}\}?/g,function(match,varName){var value=view[varName];switch(typeof value){case"string":case"number":case"boolean":return value;case"function":return value(varName);default:return""}})}function compile(template){return function(view){return render(template,view)}}exports.render=render;exports.to_html=render;exports.compile=compile;return module.exports}); | ||
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.micromustache=f()}})(function(){var define,module,exports;module={exports:exports={}};function render(template,view){if(typeof template!=="string"){return template}if(typeof view!=="object"||view===null){view={}}return template.replace(/\{\{\s*(.*?)\s*\}\}/g,function(match,varName){var path=varName.split(".");function resolve(currentScope,pathIndex){if(currentScope===null){return""}var key=path[pathIndex];var value=currentScope[key];switch(typeof value){case"string":case"number":case"boolean":return value;case"function":return value.call(view,key,currentScope,path,pathIndex);case"object":if(value===null){return""}pathIndex++;if(pathIndex<path.length){return resolve(value,pathIndex)}else{try{return JSON.stringify(value)}catch(jsonError){return"{...}"}}default:return""}}return resolve(view,0)})}function compile(template){return function compiler(view){return render(template,view)}}exports.to_html=exports.render=render;exports.compile=compile;return module.exports}); |
{ | ||
"name": "micromustache", | ||
"version": "2.2.3", | ||
"version": "3.0.0", | ||
"description": "A faster and smaller subimplementation of the {{mustache}} template engine for JavaScript", | ||
@@ -16,3 +16,2 @@ "keywords": [ | ||
"directories": { | ||
"lib": "dist", | ||
"test": "test" | ||
@@ -30,3 +29,6 @@ }, | ||
"build": "npm run build:umd && npm run build:min", | ||
"test": "mocha" | ||
"test": "mocha", | ||
"preversion": "npm test", | ||
"version": "npm run build && git add -A", | ||
"postversion": "git push && git push --tags" | ||
}, | ||
@@ -33,0 +35,0 @@ "repository": { |
110
README.md
@@ -6,14 +6,21 @@ [![GitHub issues](https://img.shields.io/github/issues/userpixel/micromustache.svg?style=flat-square)](https://github.com/userpixel/micromustache/issues) | ||
![Logo](https://raw.github.com/hanifbbz/micromustache/master/logo/micromustache-logo-300.png) | ||
![Logo](https://raw.github.com/userpixel/micromustache/master/logo/micromustache-logo-300.png) | ||
A stripped down version of the {{mustache}} template engine with JavaScript. | ||
It covers the most important use case: **replacing variable names with their values from an object**. If that's all you need, micromustache is a drop-in replacement for MustacheJS. | ||
A stripped down version of the {{mustache}} template engine with JavaScript. You don't even need to know {{mustache}} to use it. This tool covers the most important use case: **interpolation: replacing variable names with their values from an object**. | ||
![Figure 1](https://raw.github.com/userpixel/micromustache/master/fig-1.png) | ||
If that's all you need, micromustache is a drop-in replacement for MustacheJS. | ||
* No devDependencies | ||
* Works in node and Browser | ||
* Well tested | ||
* Dead simple to learn yet a pleasure to use | ||
* Well documented with many examples | ||
* Behave exactly like mustache.js for the supported functionalities | ||
You can just download it from the `browser` directory or install it with [npm] (https://npmjs.org/package/micromustache): | ||
# Installation | ||
You can just download it from the [browser directory](https://github.com/userpixel/micromustache/tree/master/browser) or install it via [npm] (https://npmjs.org/package/micromustache): | ||
```bash | ||
@@ -35,24 +42,32 @@ npm install micromustache | ||
* Partials: *{{> ...}}* | ||
* Objects as values: *{{ objName.propertyName }}* (you can use functions though) | ||
* Arrays as values: *{{ objName[propertyName] }}* (you can use functions though) | ||
* Arrays as values: *{{ arrName[1] }}* (you can access arrays like `arrName.1` though) | ||
* Inverted selection: *{{^ ...}}* | ||
* Comments: *{{! ...}}* | ||
* HTML sanitization: *{{{ propertyName }}}* | ||
* Custom delimiters: *<% ... %> instead of {{ ... }}* | ||
* Custom delimiters: *No support for <% ... %>. We just have {{ ... }}* | ||
If you can live with this, read on... | ||
# API | ||
micromustache is pretty similar to Mustache so if you know how to use Mustache, you already know Micromustache. | ||
## micromustache.render() | ||
## .render() | ||
Function signature: | ||
```js | ||
/** | ||
* @param template {string} the template containing one or more {{variableNames}} | ||
* @param [view={}] {object} an optional object containing values for every variable names | ||
* that is used in the template | ||
* @return {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); | ||
``` | ||
micromustache.render( | ||
template : String, | ||
view : Object | ||
) => String | ||
``` | ||
*Alias: to_html* | ||
*Alias: `#to_html()`* | ||
Renders a template with the provided key/values fro the view object. Example: | ||
Renders a template with the provided key/values from the view object. Example: | ||
@@ -64,18 +79,27 @@ ````js | ||
}; | ||
var output = micromustache.render('Search {{first}} {{ last }} popcorn!', person); | ||
micromustache.render('Search {{first}} {{ last }} popcorn!', person); | ||
//output = "Search Michael Jackson popcorn!" | ||
```` | ||
You can even access array elements and `length`: | ||
You can even access array elements and `length` because they are all valid keys in the array object in javascript: | ||
```js | ||
var fruits = [ "orange", "apple", "lemon" ]; | ||
var output = micromustache.render("I like {{0}}, {{1}} and {{2}} ({{length}} fruits!)", fruits); | ||
micromustache.render("I like {{0}}, {{1}} and {{2}} ({{length}} fruits!)", fruits); | ||
//output = "I like orange, apple and lemon (3 fruits!)" | ||
``` | ||
## Differences | ||
You can easily reference deep object hierarchies. | ||
For example given the [package.json](https://github.com/userpixel/micromustache/blob/master/package.json) file of this project: | ||
micromustache is a bit more liberal than MustacheJS. For example, if the `view` is `null` or `undefined`, MustacheJS throws an exception but micromustache doesn't. | ||
```js | ||
var viewObject = require('.package.json'); //or load via ajax | ||
micromustache.render("micromustache is tested with mocha version {{devDependencies.mocha}}", viewObject); | ||
//output = "^2.5.3" | ||
``` | ||
### Differences with MustacheJS render() method | ||
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: | ||
@@ -85,3 +109,4 @@ | ||
micromustache.render('{{var1}}', { | ||
var1: function (key) { | ||
var1: function (key, currentScope, path, currentPointer) { | ||
// "this" inside the function refers to the current object | ||
return key.toUpperCase(); | ||
@@ -93,11 +118,34 @@ } | ||
The function runs synchronously in the context of the view object (ie. `this` refers to the view object). | ||
The function runs synchronously in the context of the view object (i.e. `this` refers to the view object). A more complex example: | ||
## .compile() | ||
````js | ||
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}}', pathIndex); | ||
//output = 'micromustache is at http://github.com/userpixel/micromustache.git' | ||
```` | ||
## micromustache.compile() | ||
Function signature: | ||
```js | ||
/** | ||
* @param template {string} same as the template parameter to .render() | ||
* @return compiler(view) {function} a function that accepts a view and returns a rendered template | ||
*/ | ||
micromustache.compile(template); | ||
``` | ||
micromustache.compile( | ||
template : String | ||
) => String | ||
``` | ||
@@ -114,2 +162,6 @@ You can compile the template and get a function that can be used multiple times: | ||
## micromustache.to_html() | ||
Just another name for `micromustache.render()` for compatibility with MustacheJS. | ||
# Tests | ||
@@ -125,3 +177,3 @@ | ||
Add a command line version similar to | ||
* Add a command line version similar to | ||
[mustache.js](https://github.com/janl/mustache.js/blob/master/bin/mustache). |
/** | ||
* Replaces every {{variable}} inside the template with values provided by view | ||
* If the value is a function, call it passing the name of the variable as the only argument. | ||
* @param template {string} the template containing one or more {{key}} | ||
* @param view {object} an object containing string (or number) values for every key that is used in the template | ||
* @return {string} template with its valid variable names replaced with corresponding values | ||
* | ||
* @param template {string} the template containing one or more {{variableNames}} | ||
* @param [view={}] {object} an optional object containing values for every variable names | ||
* that is used in the template | ||
* @return {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 "{JSON_ERROR: ... }". | ||
*/ | ||
@@ -13,20 +17,44 @@ function render(template, view) { | ||
} | ||
//if view is not a valid object, assume it is an empty object which effectively removes all variable assignments | ||
//if view is not a valid object, assume it is an empty object | ||
//which effectively removes all variable interpolations | ||
if (typeof view !== 'object' || view === null) { | ||
view = {}; | ||
} | ||
return template.replace(/\{?\{\{\s*(.*?)\s*\}\}\}?/g, function(match, varName) { | ||
var value = view[varName]; | ||
switch (typeof value) { | ||
case 'string': | ||
case 'number': | ||
case 'boolean': | ||
return value; | ||
case 'function': | ||
//if the value is a function, call it passing the variable name | ||
return value.call(view, varName); | ||
default: | ||
//anything else will be replaced with an empty string. This includes object, array, date, regexp and null. | ||
return template.replace(/\{\{\s*(.*?)\s*\}\}/g, function(match, varName) { | ||
var path = varName.split('.'); | ||
function resolve(currentScope, pathIndex) { | ||
if (currentScope === null) { | ||
return ''; | ||
} | ||
var key = path[pathIndex]; | ||
var value = currentScope[key]; | ||
switch (typeof value) { | ||
case 'string': | ||
case 'number': | ||
case 'boolean': | ||
return value; | ||
case 'function': | ||
//if the value is a function, call it passing the variable name | ||
return value.call(view, key, currentScope, path, pathIndex); | ||
case 'object': | ||
if (value === null) { | ||
return ''; | ||
} | ||
pathIndex++; | ||
if ( pathIndex < path.length ) { | ||
return resolve(value, pathIndex); | ||
} else { | ||
try { | ||
return JSON.stringify(value); | ||
} catch (jsonError) { | ||
return '{...}'; | ||
} | ||
} | ||
default: | ||
//anything else will be replaced with an empty string (date, regexp, etc). | ||
return ''; | ||
} | ||
} | ||
return resolve(view, 0); | ||
}); | ||
@@ -36,15 +64,17 @@ } | ||
/** | ||
* This function really doesn't make things particularly faster. | ||
* However it makes the repeated calls shorter! | ||
* @param template {string} the template containing one or more {{key}} | ||
* @return {function} a function that calls render(template, view) under the hood | ||
* This function makes repeated calls shorter by returning a compiler function | ||
* for a particular template that accepts data and returnes the rendered string. | ||
* It doesn't make the code faster since the compiler still uses render internally. | ||
* | ||
* @param template {string} same as the template parameter to render() | ||
* @return compiler(view) {function} a function that accepts a view and returns a rendered template | ||
*/ | ||
function compile(template) { | ||
function compile (template) { | ||
//create and return a function that will always apply this template under the hood | ||
return function(view) { | ||
return render(template, view); | ||
return function compiler (view) { | ||
return render (template, view); | ||
}; | ||
} | ||
exports.to_html = exports.render = render;; | ||
exports.to_html = exports.render = render; | ||
exports.compile = compile; |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
46255
10
174
173