template-helpers NPM version Build Status

Generic JavaScript helpers that can be used with any template engine. Handlebars, Lo-Dash, Underscore, or any engine that supports helper functions.

Install with npm

npm i template-helpers --save

TOC

(Table of contents generated by verb)

Usage

To get all helpers grouped by collection:

var helpers = require('template-helpers');

// All helpers are on the `_` property
console.log(helpers._);

Get a specific collection

var helpers = require('template-helpers');

// get only the math helpers
var math = helpers.math;

Use with any template engine

Lo-Dash Example

var context = {arr: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']};

// pass helpers on `imports`
var imports = {imports: helpers.arrays};
var template = _.template('<%= first(foo) %>', imports);

// pass context
template({foo: ['a', 'b', 'c']});
//=> 'a'

Namespacing

Handlebars and Lo-Dash both allow dot notation to be used for referencing helpers. Other engines may allow this too, I'd be happy to add this information to readme 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.

Code coverage

Statements   : 97.58% ( 363/372 )
Branches     : 96.92% ( 189/195 )
Functions    : 98.78% ( 81/82 )
Lines        : 97.2% ( 312/321 )

Docs

.isArray

Returns true if value is an array.

Params

Example

<%= isArray('a, b, c') %>
//=> 'false'

<%= isArray(['a, b, c']) %>
//=> 'true'

.arrayify

Cast val to an array.

Params

Example

<%= arrayify('a') %>
//=> '["a"]'

<%= arrayify({a: 'b'}) %>
//=> '[{a: "b"}]'

<%= arrayify(['a')] %>
//=> '["a"]'

.first

Returns the first item, or first n items of an array.

Params

Example

<%= first(['a', 'b', 'c', 'd', 'e'], 2) %>
//=> '["a", "b"]'

.last

Returns the last item, or last n items of an array.

Params

Example

<%= last(['a', 'b', 'c', 'd', 'e'], 2) %>
//=> '["d", "e"]'

.before

Returns all of the items in an array up to the specified number Opposite of <%= after() %.

Params

Example

<%= before(['a', 'b', 'c'], 2) %>
//=> '["a", "b"]'

.after

Returns all of the items in an arry after the specified index. Opposite of <%= before() %.

Params

Example

<%= after(['a', 'b', 'c'], 1) %>
//=> '["c"]'

.map

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

Examples

function double(str) {
  return str + str;
}
<%= map(['a', 'b', 'c'], double) %>
//=> '["aa", "bb", "cc"]'

.join

Join all elements of array into a string, optionally using a given separator.

Params

Example

<%= join(['a', 'b', 'c']) %>
//=> 'a, b, c'

<%= join(['a', 'b', 'c'], '-') %>
//=> 'a-b-c'

.sort

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

Example

<%= sort(["b", "a", "c"]) %>
//=> 'a,b,c'

<%= sort([{a: "zzz"}, {a: "aaa"}], "a") %>
//=> '[{"a":"aaa"},{"a":"zzz"}]'

.length

Returns the length of the given array.

Params

Example

<%= length(['a', 'b', 'c']) %>
//=> 3

.compact

Returns an array with all falsey values removed.

Params

Example

<%= compact([null, a, undefined, 0, false, b, c, '']) %>
//=> '["a", "b", "c"]'

.difference

Return the difference between the first array and additional arrays.

Params

Example

<%= difference(["a", "c"], ["a", "b"]) %>
//=> '["c"]'

.unique

Return an array, free of duplicate values.

Params

Example

<%= unique(['a', 'b', 'c', 'c']) %
=> '["a", "b", "c"]'

.union

Returns an array of unique values using strict equality for comparisons.

Params

Example

<%= union(["a"], ["b"], ["c"]) %>
//=> '["a", "b", "c"]'

.shuffle

Shuffle the items in an array.

Params

Example

<%= shuffle(["a", "b", "c"]) %>
//=> ["c", "a", "b"]

.embed

Embed code from an external file as preformatted text.

Params

Example

<%= embed('path/to/file.js') %>

// specify the language to use
<%= embed('path/to/file.hbs', 'html') %>

.jsfiddle

Generate the HTML for a jsFiddle link with the given params

Params

Example

<%= jsfiddle({id: '0dfk10ks', {tabs: true}}) %>

.any

Returns true if value exists in the given string, array or object. See any for documentation.

Params

._if

Return true if key is an own, enumerable property of the given obj.

Params

.read

Read a file from the file system and inject its content

Params

Example

<%= read("foo.js") %>

.escapeHtml

Escape HTML characters in a string.

Params

Example

<%= escapeHtml("<span>foo</span>") %>
//=> &lt;span&gt;foo&lt;&#x2F;span&gt;

.sanitize

Strip HTML tags from a string, so that only the text nodes are preserved.

Params

Example

<%= sanitize("<span>foo</span>") %>
//=> 'foo'

.add

Return the product of a plus b.

Params

Example

<%= add(1, 2) %>
//=> '3'

.subtract

Subtract b from a.

Params

Example

<%= subtract(5, 2) %>
//=> '3'

.divide

Divide a (the numerator) by b (the divisor).

Params

Example

<%= divide(10, 2) %>
//=> '5'

.multiply

Multiply a by b.

Params

Example

<%= divide(10, 2) %>
//=> '5'

.floor

Returns the largest integer less than or equal to the given number.

Params

Example

<%= floor(10.6) %>
//=> '10'

.ceil

Returns the smallest integer greater than or equal to the given number.

Params

Example

<%= ceil(10.1) %>
//=> '11'

.round

Returns the value of the given number rounded to the nearest integer.

Params

Example

<%= round(10.1) %>
//=> '10'

<%= round(10.5) %>
//=> '11'

.sum

Returns the sum of all numbers in the given array.

Params

Example

<%= sum([1, 2, 3, 4, 5]) %>
//=> '15'

.fallback

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

Example

// when `title` is undefined, use the generic `site.title`
<%= fallback(page.title, site.title) %>

.stringify

Stringify an object using JSON.stringify().

Params

Example

<%= stringify({a: "a"}) %>
//=> '{"a":"a"}'

.parse

Parse a string into an object using JSON.parse().

Params

Example

<%= parse('{"foo":"bar"}')["foo"] %>
//=> 'bar'

.get

Use property paths (a.b.c) get a nested value from an object.

Params

Example

<%= get({a: {b: 'c'}}, 'a.b') %>
//=> 'c'

.keys

Returns an array of keys from the given object.

Params

Example

<%= keys({a: 'b', c: 'd'}) %>
//=> '["a", "c"]'

.isObject

Return true if the given value is an object, and not null or an array.

Params

Example

<%= isObject(['a', 'b', 'c']) %>
//=> 'false'

<%= isObject({a: 'b'}) %>
//=> 'true'

.isPlainObject

Return true if the given value is a plain object.

Params

Example

<%= isPlainObject(['a', 'b', 'c']) %>
//=> 'false'

<%= isPlainObject({a: 'b'}) %>
//=> 'true'

<%= isPlainObject(/foo/g) %>
//=> 'false'

.hasOwn

Return true if key is an own, enumerable property of the given obj.

Params

.omit

Return a copy of object exclusing the given keys.

Params

Example

<%= omit({a: 'a', b: 'b', c: 'c'}, ['a', 'c']) %>
//=> '{b: "b"}'

.extend

Extend o with properties of other objects.

Params

.merge

Recursively combine the properties of o with the properties of other objects.

Params

.dirname

Return the dirname for the given filepath. Uses the node.js path module.

Params

Example

<%= dirname("a/b/c/d") %>
//=> 'a/b/c'

.basename

Return the basename for the given filepath. Uses the node.js path module.

Params

Example

<%= basename("a/b/c/d.js") %>
//=> 'd.js'

.filename

Return the filename for the given filepath, excluding extension.

Params

Example

<%= basename("a/b/c/d.js") %>
//=> 'd'

.extname

Return the file extension for the given filepath. Uses the node.js path module.

Params

Example

<%= extname("foo.js") %>
//=> '.js'

.ext

Return the file extension for the given filepath, excluding the ..

Params

Example

<%= ext("foo.js") %>
//=> 'js'

.resolve

Resolves the given paths to an absolute path. Uses the node.js path module.

Params

Example

<%= resolve('/foo/bar', './baz') %>
//=> '/foo/bar/baz'

.relative

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

Example

<%= relative(a, b) %>

.segments

Get specific (joined) segments of a file path by passing a range of array indices.

Params

Example

<%= segments("a/b/c/d", "2", "3") %>
//=> 'c/d'

<%= segments("a/b/c/d", "1", "3") %>
//=> 'b/c/d'

<%= segments("a/b/c/d", "1", "2") %>
//=> 'b/c'

.join

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

Example

<%= join("a", "b") %>
//=> 'a/b'

.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

Example

// posix
<%= isAbsolute('/foo/bar') %>
//=> 'true'
<%= isAbsolute('qux/') %>
//=> 'false'
<%= isAbsolute('.') %>
//=> 'false'

// Windows
<%= isAbsolute('//server') %>
//=> 'true'
<%= isAbsolute('C:/foo/..') %>
//=> 'true'
<%= isAbsolute('bar\\baz') %>
//=> 'false'
<%= isAbsolute('.') %>
//=> 'false'

.isRelative

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

Example

// posix
<%= isRelative('/foo/bar') %>
//=> 'false'
<%= isRelative('qux/') %>
//=> 'true'
<%= isRelative('.') %>
//=> 'true'

// Windows
<%= isRelative('//server') %>
//=> 'false'
<%= isRelative('C:/foo/..') %>
//=> 'false'
<%= isRelative('bar\\baz') %>
//=> 'true'
<%= isRelative('.') %>
//=> 'true'

.isString

Returns true if the value is a string.

Params

Example

<%= isString('abc') %>
//=> 'true'

<%= isString(null) %>
//=> 'false'

.lowercase

Lowercase the characters in the given string.

Params

Example

<%= lowercase("ABC") %>
//=> 'abc'

.uppercase

Uppercase the characters in a string.

Params

Example

<%= uppercase("abc") %>
//=> 'ABC'

.trim

Trim extraneous whitespace from the beginning and end of a string.

Params

Example

<%= trim("  ABC   ") %>
//=> 'ABC'

.chop

Like trim, but removes both extraneous whitespace and non-word characters from the beginning and end of a string.

Params

Example

<%= chop("_ABC_") %>
//=> 'ABC'

<%= chop("-ABC-") %>
//=> 'ABC'

<%= chop(" ABC ") %>
//=> 'ABC'

.stripIndent

Strip the indentation from a string.

Params

Example

<%= stripIndent("  _ABC_") %>
//=> 'ABC'

.camelcase

camelCase the characters in string.

Params

Example

<%= camelcase("foo bar baz") %>
//=> 'fooBarBaz'

.pascalcase

PascalCase the characters in string.

Params

Example

<%= pascalcase("foo bar baz") %>
//=> 'FooBarBaz'

.snakecase

snake_case the characters in string.

Params

Example

<%= snakecase("a-b-c d_e") %>
//=> 'a_b_c_d_e'

.dotcase

dot.case the characters in string.

Params

Example

<%= dotcase("a-b-c d_e") %>
//=> 'a.b.c.d.e'

.dashcase

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

Example

<%= dashcase("a b.c d_e") %>
//=> 'a-b-c-d-e'

.pathcase

path/case the characters in string.

Params

Example

<%= pathcase("a-b-c d_e") %>
//=> 'a/b/c/d/e'

.sentencecase

Sentence-case the characters in string.

Params

Example

<%= sentencecase("foo bar baz.") %>
//=> 'Foo bar baz.'

.hyphenate

Replace spaces in a string with hyphens. This

Params

Example

<%= hyphenate("a b c") %>
//=> 'a-b-c'

.wordwrap

Wrap words to a specified width using word-wrap.

Params

Example

<%= wordwrap("a b c d e f", {width: 5, newline: '<br>  '}) %>
//=> '  a b c <br>  d e f'

.count

Count the number of occurrances of a substring within a string.

Params

Example

<%= count("abcabcabc", "a") %>
//=> '3'

.reverse

Reverse the characters in a string.

Params

Example

<%= reverse("abc") %>
//=> 'cba'

.rightAlign

Right align the characters in a string using non-breaking spaces.

Params

Example

<%= rightAlign(str) %>

.centerAlign

Center align the characters in a string using non-breaking spaces.

Params

Example

<%= centerAlign("abc") %>

.replace

Replace occurrences of a with b.

Params

Example

<%= replace("abcabc", /a/, "z") %>
//=> 'zbczbc'

.truncate

Truncate a string by removing all HTML tags and limiting the result to the specified length.

Params

Example

<%= truncate("<span>foo bar baz</span>", 7) %>
//=> 'foo bar'

.ellipsis

Truncate a string to the specified length, and append it with an elipsis, .

Params

Example

<%= ellipsis("<span>foo bar baz</span>", 7) %>
//=> 'foo bar…'

Related projects

Also take a look at the helpers org, there are dozens of specialized helpers that can be downloaded individually.

Running tests

Install dev dependencies:

npm i -d && npm test

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue

Author

Jon Schlinkert

License

Copyright (c) 2015 Jon Schlinkert Released under the MIT license.


This file was generated by verb-cli on April 25, 2015.