template-helpers

Generic JavaScript helpers that can be used with any template engine. Handlebars, Lo-Dash, Underscore, or any engine that supports helper functions.
Install
Install with npm:
$ npm install template-helpers --save
In addition to the related projects listed below, also take a look at the helpers org, there are 60+ specialized helpers that can be used individually.
Usage
To get all helpers:
var helpers = require('template-helpers')();
console.log(helpers);
Get a specific helper category
var helpers = require('template-helpers')('math');
Get multiple helper categories
var helpers = require('template-helpers')(['math', 'string']);
Use with any template engine
Lo-Dash Example
var helpers = require('template-helpers')('array');
var imports = {imports: helpers};
var fn = _.template('<%= first(foo) %>', imports);
fn({foo: ['a', 'b', 'c']});
Namespacing
Handlebars and Lo-Dash both allow dot notation to be used for referencing helpers. I'd be happy to add examples for other engines if someone wants to do a PR.
Example
<%= path.dirname("a/b/c/d.js") %>
This can be used as a way of working around potential naming conflicts.
API
Returns true if value is an array.
Params
value {any}: The value to test.
returns {Boolean}
Example
<%= isArray('a, b, c') %>
<%= isArray(['a, b, c']) %>
Cast val to an array.
Params
val {any}: The value to arrayify.
returns {Array}: An array.
returns {Array}
Example
<%= arrayify('a') %>
<%= arrayify({a: 'b'}) %>
<%= arrayify(['a']) %>
Returns the first item, or first n items of an array.
Params
array {Array}
n {Number}: Number of items to return, starting at 0.
returns {Array}
Example
<%= first(['a', 'b', 'c', 'd', 'e'], 2) %>
Returns the last item, or last n items of an array.
Params
array {Array}
n {Number}: Number of items to return, starting with the last item.
returns {Array}
Example
<%= last(['a', 'b', 'c', 'd', 'e'], 2) %>
Returns all of the items in an array up to the specified number Opposite of <%= after() %.
Params
array {Array}
n {Number}
returns {Array}: Array excluding items after the given number.
Example
<%= before(['a', 'b', 'c'], 2) %>
Returns all of the items in an arry after the specified index. Opposite of <%= before() %.
Params
array {Array}: Collection
n {Number}: Starting index (number of items to exclude)
returns {Array}: Array exluding n items.
Example
<%= after(['a', 'b', 'c'], 1) %>
Calling fn on each element of the given array with the given context.
Assuming that double has been registered as a helper:
Params
array {Array}
fn {String}: The function to call on each element in the given array.
returns {String}
Examples
function double(str) {
return str + str;
}
<%= each(['a', 'b', 'c'], double, ctx) %>
Returns a new array, created by calling function on each element of the given array.
Assuming that double has been registered as a helper:
Params
array {Array}
fn {String}: The function to call on each element in the given array.
returns {String}
Examples
function double(str) {
return str + str;
}
<%= map(['a', 'b', 'c'], double) %>
Join all elements of array into a string, optionally using a given separator.
Params
array {Array}
sep {String}: The separator to use.
returns {String}
Example
<%= join(['a', 'b', 'c']) %>
<%= join(['a', 'b', 'c'], '-') %>
Sort the given array. If an array of objects is passed, you may optionally pass a key to sort on as the second argument. You may alternatively pass a sorting function as the second argument.
Params
array {Array}: the array to sort.
key {String|Function}: The object key to sort by, or sorting function.
Example
<%= sort(["b", "a", "c"]) %>
<%= sort([{a: "zzz"}, {a: "aaa"}], "a") %>
Returns the length of the given array.
Params
array {Array}
returns {Number}: The length of the array.
Example
<%= length(['a', 'b', 'c']) %>
Returns an array with all falsey values removed.
Params
arr {Array}
returns {Array}
Example
<%= compact([null, a, undefined, 0, false, b, c, '']) %>
Return the difference between the first array and additional arrays.
Params
array {Array}: The array to compare againts.
arrays {Array}: One or more additional arrays.
returns {Array}
Example
<%= difference(["a", "c"], ["a", "b"]) %>
Return an array, free of duplicate values.
Params
array {Array}: The array to uniquify
returns {Array}: Duplicate-free array
Example
<%= unique(['a', 'b', 'c', 'c']) %
=> '["a", "b", "c"]'
Returns an array of unique values using strict equality for comparisons.
Params
arr {Array}
returns {Array}
Example
<%= union(["a"], ["b"], ["c"]) %>
Shuffle the items in an array.
Params
arr {Array}
returns {Array}
Example
<%= shuffle(["a", "b", "c"]) %>
Embed code from an external file as preformatted text.
Params
fp {String}: filepath to the file to embed.
language {String}: Optionally specify the language to use for syntax highlighting.
returns {String}
Example
<%= embed('path/to/file.js') %>
<%= embed('path/to/file.hbs', 'html') %>
Generate the HTML for a jsFiddle link with the given params
Params
params {Object}
returns {String}
Example
<%= jsfiddle({id: '0dfk10ks', {tabs: true}}) %>
Returns true if value exists in the given string, array
or object. See [any] for documentation.
Params
value {any}
target {any}
options {Object}
Return true if key is an own, enumerable property
of the given obj.
Params
object {Object}
key {String}
returns {Boolean}
Return true if a file exists
Params
filepath {String}: Path of the file to check.
returns {Boolean}: True if the file exists
Example
<%= exists("foo.js") %>
Read a file from the file system and inject its content
Params
filepath {String}: Path of the file to read.
returns {String}: Contents of the given file.
Example
<%= read("foo.js") %>
Escape HTML characters in a string.
Params
str {String}: String of HTML with characters to escape.
returns {String}
Example
<%= escapeHtml("<span>foo</span>") %>
Strip HTML tags from a string, so that only the text nodes are preserved.
Params
str {String}: The string of HTML to sanitize.
returns {String}
Example
<%= sanitize("<span>foo</span>") %>
Return the product of a plus b.
Params
Example
<%= add(1, 2) %>
Subtract b from a.
Params
Example
<%= subtract(5, 2) %>
Divide a (the numerator) by b (the divisor).
Params
a {Number}: the numerator.
b {Number}: the divisor.
returns {Number}: The quotient of a divided by b.
Example
<%= divide(10, 2) %>
Multiply a by b.
Params
a {Number}
b {Number}
returns {Number}: The product of a times b.
Example
<%= divide(10, 2) %>
Returns the largest integer less than or equal to the given number.
Params
number {Number}
returns {Number}
Example
<%= floor(10.6) %>
Returns the smallest integer greater than or equal to the given number.
Params
number {Number}
returns {Number}
Example
<%= ceil(10.1) %>
Returns the value of the given number rounded to the nearest integer.
Params
number {Number}
returns {Number}
Example
<%= round(10.1) %>
<%= round(10.5) %>
Returns the sum of all numbers in the given array.
Params
number {Number}
returns {Number}
Example
<%= sum([1, 2, 3, 4, 5]) %>
Specify a fallback value to use when the desired value is undefined. Note that undefined variables that are not object properties with throw an error.
Params
a {any}: The desired value.
b {any}: The fallback ("default") value
returns {any}: Either a or b
Example
<%= fallback(page.title, site.title) %>
Stringify an object using JSON.stringify().
Params
object {Object}
returns {String}
Example
<%= stringify({a: "a"}) %>
Parse a string into an object using JSON.parse().
Params
str {String}: The string to parse.
returns {Object}: The parsed object.
Example
<%= parse('{"foo":"bar"}')["foo"] %>
Use property paths (a.b.c) get a nested value from an object.
Params
object {Object}
path {String}: Dot notation for the property to get.
returns {String}
Example
<%= get({a: {b: 'c'}}, 'a.b') %>
Returns an array of keys from the given object.
Params
object {Object}
returns {Array}: Keys from object
Example
<%= keys({a: 'b', c: 'd'}) %>
Return true if the given value is an object, and not null or an array.
Params
value {Object}: The value to check.
returns {Boolean}
Example
<%= isObject(['a', 'b', 'c']) %>
<%= isObject({a: 'b'}) %>
Return true if the given value is a plain object.
Params
value {Object}: The value to check.
returns {Boolean}
Example
<%= isPlainObject(['a', 'b', 'c']) %>
<%= isPlainObject({a: 'b'}) %>
<%= isPlainObject(/foo/g) %>
Return true if key is an own, enumerable property
of the given obj.
Params
object {Object}
key {String}
returns {Boolean}
Return a copy of object exclusing the given keys.
Params
object {Object}: Object with keys to omit.
keys {String}: Keys to omit.
returns {Boolean}
Example
<%= omit({a: 'a', b: 'b', c: 'c'}, ['a', 'c']) %>
Return a copy of object exclusing the given keys.
Params
object {Object}: Object with keys to omit.
keys {String}: Keys to omit.
returns {Boolean}
Example
<%= omit({a: 'a', b: 'b', c: 'c'}, ['a', 'c']) %>
Return a copy of object exclusing the given keys.
Params
object {Object}: Object with keys to omit.
keys {String}: Keys to omit.
returns {Boolean}
Example
<%= omit({a: 'a', b: 'b', c: 'c'}, ['a', 'c']) %>
Extend o with properties of other objects.
Params
o {Object}: The target object. Pass an empty object to shallow clone.
objects {Object}
returns {Object}
Recursively combine the properties of o with the
properties of other objects.
Params
o {Object}: The target object. Pass an empty object to shallow clone.
objects {Object}
returns {Object}
Return the dirname for the given filepath. Uses the node.js path module.
Params
filepath {String}
returns {String}: Returns the directory part of the file path.
Example
<%= dirname("a/b/c/d") %>
Return the basename for the given filepath. Uses the node.js path module.
Params
filepath {String}
returns {String}: Returns the basename part of the file path.
Example
<%= basename("a/b/c/d.js") %>
Return the filename for the given filepath, excluding extension.
Params
filepath {String}
returns {String}: Returns the file name part of the file path.
Example
<%= basename("a/b/c/d.js") %>
Return the file extension for the given filepath. Uses the node.js path module.
Params
filepath {String}
returns {String}: Returns a file extension
Example
<%= extname("foo.js") %>
Return the file extension for the given filepath, excluding the ..
Params
filepath {String}
returns {String}: Returns a file extension without dot.
Example
<%= ext("foo.js") %>
Resolves the given paths to an absolute path. Uses the node.js path module.
Params
filepath {String}
returns {String}: Returns a resolve
Example
<%= resolve('/foo/bar', './baz') %>
Get the relative path from file a to file b. Typically a and b would be variables passed on the context. Uses the node.js path module.
Params
a {String}: The "from" file path.
b {String}: The "to" file path.
returns {String}: Returns a relative path.
Example
<%= relative(a, b) %>
Get specific (joined) segments of a file path by passing a range of array indices.
Params
filepath {String}: The file path to split into segments.
returns {String}: Returns a single, joined file path.
Example
<%= segments("a/b/c/d", "2", "3") %>
<%= segments("a/b/c/d", "1", "3") %>
<%= segments("a/b/c/d", "1", "2") %>
Join all arguments together and normalize the resulting filepath. Uses the node.js path module.
Note: there is also a join() array helper, dot notation
can be used with helpers to differentiate. Example: <%= path.join() %>.
Params
filepaths {String}: List of file paths.
returns {String}: Returns a single, joined file path.
Example
<%= join("a", "b") %>
Returns true if a file path is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. Uses the node.js path module.
Params
filepath {String}
returns {String}: Returns a resolve
Example
<%= isAbsolute('/foo/bar') %>
<%= isAbsolute('qux/') %>
<%= isAbsolute('.') %>
<%= isAbsolute('//server') %>
<%= isAbsolute('C:/foo/..') %>
<%= isAbsolute('bar\\baz') %>
<%= isAbsolute('.') %>
Returns true if a file path is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. Uses the node.js path module.
Params
filepath {String}
returns {String}: Returns a resolve
Example
<%= isRelative('/foo/bar') %>
<%= isRelative('qux/') %>
<%= isRelative('.') %>
<%= isRelative('//server') %>
<%= isRelative('C:/foo/..') %>
<%= isRelative('bar\\baz') %>
<%= isRelative('.') %>
camelCase the characters in string.
Params
string {String}: The string to camelcase.
returns {String}
Example
<%= camelcase("foo bar baz") %>
Center align the characters in a string using non-breaking spaces.
Params
str {String}: The string to reverse.
returns {String}: Centered string.
Example
<%= centerAlign("abc") %>
Like trim, but removes both extraneous whitespace and non-word characters from the beginning and end of a string.
Params
string {String}: The string to chop.
returns {String}
Example
<%= chop("_ABC_") %>
<%= chop("-ABC-") %>
<%= chop(" ABC ") %>
Count the number of occurrances of a substring within a string.
Params
string {String}
substring {String}
returns {Number}: The occurances of substring in string
Example
<%= count("abcabcabc", "a") %>
dot.case the characters in string.
Params
string {String}
returns {String}
Example
<%= dotcase("a-b-c d_e") %>
Truncate a string to the specified length, and append it with an elipsis, ….
Params
str {String}
length {Number}: The desired length of the returned string.
ch {String}: Optionally pass custom characters to append. Default is ….
returns {String}: The truncated string.
Example
<%= ellipsis("<span>foo bar baz</span>", 7) %>
Returns true if the value is a string.
Params
val {String}
returns {Boolean}: True if the value is a string.
Example
<%= isString('abc') %>
<%= isString(null) %>
Lowercase the characters in the given string.
Params
string {String}: The string to lowercase.
returns {String}
Example
<%= lowercase("ABC") %>
PascalCase the characters in string.
Params
string {String}
returns {String}
Example
<%= pascalcase("foo bar baz") %>
snake_case the characters in string.
Params
string {String}
returns {String}
Example
<%= snakecase("a-b-c d_e") %>
Split string by the given character.
Params
string {String}: The string to split.
returns {String} character: Default is ,
Example
<%= split("a,b,c", ",") %>
Strip the indentation from a string.
Params
string {String}: The string to strip indentation from.
returns {String}
Example
<%= stripIndent(" _ABC_") %>
Trim extraneous whitespace from the beginning and end of a string.
Params
string {String}: The string to trim.
returns {String}
Example
<%= trim(" ABC ") %>
dash-case the characters in string. This is similar to [slugify], but [slugify] makes the string compatible to be used as a URL slug.
Params
string {String}
returns {String}
Example
<%= dashcase("a b.c d_e") %>
path/case the characters in string.
Params
string {String}
returns {String}
Example
<%= pathcase("a-b-c d_e") %>
Sentence-case the characters in string.
Params
string {String}
returns {String}
Example
<%= sentencecase("foo bar baz.") %>
Replace spaces in a string with hyphens. This
Params
string {String}
returns {String}
Example
<%= hyphenate("a b c") %>
Reverse the characters in a string.
Params
str {String}: The string to reverse.
returns {String}
Example
<%= reverse("abc") %>
Right align the characters in a string using non-breaking spaces.
Params
str {String}: The string to reverse.
returns {String}: Right-aligned string.
Example
<%= rightAlign(str) %>
Replace occurrences of a with b.
Params
str {String}
a {String|RegExp}: Can be a string or regexp.
b {String}
returns {String}
Example
<%= replace("abcabc", /a/, "z") %>
Truncate a string by removing all HTML tags and limiting the result to the specified length.
Params
str {String}
length {Number}: The desired length of the returned string.
returns {String}: The truncated string.
Example
<%= titlecase("big deal") %>
Truncate a string by removing all HTML tags and limiting the result to the specified length.
Params
str {String}
length {Number}: The desired length of the returned string.
returns {String}: The truncated string.
Example
<%= truncate("<span>foo bar baz</span>", 7) %>
Uppercase the characters in a string.
Params
string {String}: The string to uppercase.
returns {String}
Example
<%= uppercase("abc") %>
Wrap words to a specified width using word-wrap.
Params
string {String}: The string with words to wrap.
object {Options}: Options to pass to word-wrap
returns {String}: Formatted string.
Example
<%= wordwrap("a b c d e f", {width: 5, newline: '<br> '}) %>
Returns true if the given val is an object.
Params
val {any}
returns {Boolean}
Example
utils.isObject('foo');
utils.isObject({});
Stringify HTML tag attributes from the given object.
Params
object {Object}: Object of attributes as key-value pairs.
returns {String}: Stringified attributes, e.g. foo="bar"
Code coverage
Statements : 94.61% ( 439/464 )
Branches : 88.37% ( 190/215 )
Functions : 96.94% ( 95/98 )
Lines : 94.42% ( 389/412 )
Related projects
You might also be interested in these projects:
- assemble: Assemble is a powerful, extendable and easy to use static site generator for node.js. Used… more | homepage
- handlebars-helpers: 120+ Handlebars helpers in ~20 categories, for Assemble, YUI, Ghost or any Handlebars project. Includes… more | homepage
- helper-cache: Easily register and get helper functions to be passed to any template engine or node.js… more | homepage
- template: Render templates using any engine. Supports, layouts, pages, partials and custom template types. Use template… more | homepage
- utils: Fast, generic JavaScript/node.js utility functions. | homepage
- verb: Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… more | homepage
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Building docs
Generate readme and API documentation with verb:
$ npm install verb && npm run docs
Or, if verb is installed globally:
$ verb
Running tests
Install dev dependencies:
$ npm install -d && npm test
Author
Jon Schlinkert
License
Copyright © 2016, Jon Schlinkert.
Released under the MIT license.
This file was generated by verb, v0.9.0, on April 25, 2016.