Git Product home page Git Product logo

handlebars-helpers's Introduction

handlebars-helpers NPM version NPM monthly downloads NPM total downloads Linux Build Status Windows Build Status

More than 130 Handlebars helpers in ~20 categories. Helpers can be used with Assemble, Generate, Verb, Ghost, gulp-handlebars, grunt-handlebars, consolidate, or any node.js/Handlebars project.

You might also be interested in template-helpers.

Install

Install with npm:

$ npm install --save handlebars-helpers

Install with yarn:

$ yarn add handlebars-helpers

Browser usage

See how to use handlebars-helpers in the browser.

Usage

The main export returns a function that needs to be called to expose the object of helpers.

Get all helpers

var helpers = require('handlebars-helpers')();
//=> returns object with all (130+) helpers

Get a specific helper collection

Helper collections are exposed as getters, so only the helpers you want will be required and loaded.

var helpers = require('handlebars-helpers');
var math = helpers.math();
//=> only the `math` helpers

var helpers = require('handlebars-helpers');
var array = helpers.array();
//=> only the `collections` helpers

Get multiple helpers collections

Helper collections are exposed as getters, so only the helpers you want will be required and loaded.

var helpers = require('handlebars-helpers')(['math', 'string']);
//=> only the `math` and `string` helpers

Optionally pass your own handlebars

var handlebars = require('handlebars');
var helpers = require('handlebars-helpers')({
  handlebars: handlebars
});

// or for a specific collection
var math = helpers.math({
  handlebars: handlebars
});

Helpers

Categories

Currently 189 helpers in 20 categories:

All helpers

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)

Visit the: code | unit tests | issues)


array

Returns all of the items in an array 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

<!-- array: ['a', 'b', 'c'] -->
{{after array 1}}
<!-- results in: '["c"]' -->

Cast the given value to an array.

Params

  • value {any}
  • returns {Array}

Example

{{arrayify "foo"}}
<!-- results in: [ "foo" ] -->

Return all of the items in the collection before the specified count. Opposite of after.

Params

  • array {Array}
  • n {Number}
  • returns {Array}: Array excluding items after the given number.

Example

<!-- array: ['a', 'b', 'c'] -->
{{before array 2}}
<!-- results in: '["a", "b"]' -->

Params

  • array {Array}
  • options {Object}
  • returns {String}

Example

<!-- array: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] -->
{{#eachIndex array}}
  {{item}} is {{index}}
{{/eachIndex}}

Block helper that filters the given array and renders the block for values that evaluate to true, otherwise the inverse block is returned.

Params

  • array {Array}
  • value {any}
  • options {Object}
  • returns {String}

Example

<!-- array: ['a', 'b', 'c'] -->
{{#filter array "foo"}}AAA{{else}}BBB{{/filter}}
<!-- results in: 'BBB' -->

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}}
<!-- results in: '["a", "b"]' -->

Iterates over each item in an array and exposes the current item in the array as context to the inner block. In addition to the current array item, the helper exposes the following variables to the inner block:

  • index
  • total
  • isFirst
  • isLast Also, @index is exposed as a private variable, and additional private variables may be defined as hash arguments.

Params

  • array {Array}
  • returns {String}

Example

<!-- accounts = [
{'name': 'John', 'email': '[email protected]'},
{'name': 'Malcolm', 'email': '[email protected]'},
{'name': 'David', 'email': '[email protected]'}
] -->

{{#forEach accounts}}
  <a href="mailto:{{ email }}" title="Send an email to {{ name }}">
    {{ name }}
  </a>{{#unless isLast}}, {{/unless}}
{{/forEach}}

Block helper that renders the block if an array has the given value. Optionally specify an inverse block to render when the array does not have the given value.

Params

  • array {Array}
  • value {any}
  • options {Object}
  • returns {String}

Example

<!-- array: ['a', 'b', 'c'] -->
{{#inArray array "d"}}
  foo
{{else}}
  bar
{{/inArray}}
<!-- results in: 'bar' -->

Returns true if value is an es5 array.

Params

  • value {any}: The value to test.
  • returns {Boolean}

Example

{{isArray "abc"}}
<!-- results in: false -->

<!-- array: [1, 2, 3] -->
{{isArray array}}
<!-- results in: true -->

Returns the item from array at index idx.

Params

  • array {Array}
  • idx {Number}
  • returns {any} value

Example

<!-- array: ['a', 'b', 'c'] -->
{{itemAt array 1}}
<!-- results in: 'b' -->

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

Params

  • array {Array}
  • separator {String}: The separator to use. Defaults to ,.
  • returns {String}

Example

<!-- array: ['a', 'b', 'c'] -->
{{join array}}
<!-- results in: 'a, b, c' -->

{{join array '-'}}
<!-- results in: 'a-b-c' -->

Returns true if the the length of the given value is equal to the given length. Can be used as a block or inline helper.

Params

  • value {Array|String}
  • length {Number}
  • options {Object}
  • returns {String}

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

Params

  • value {Array|String}: Array or string.
  • n {Number}: Number of items to return from the end of the array.
  • returns {Array}

Example

<!-- var value = ['a', 'b', 'c', 'd', 'e'] -->

{{last value}}
<!-- results in: ['e'] -->

{{last value 2}}
<!-- results in: ['d', 'e'] -->

{{last value 3}}
<!-- results in: ['c', 'd', 'e'] -->

Returns the length of the given string or array.

Params

  • value {Array|Object|String}
  • returns {Number}: The length of the value.

Example

{{length '["a", "b", "c"]'}}
<!-- results in: 3 -->

<!-- results in: myArray = ['a', 'b', 'c', 'd', 'e']; -->
{{length myArray}}
<!-- results in: 5 -->

<!-- results in: myObject = {'a': 'a', 'b': 'b'}; -->
{{length myObject}}
<!-- results in: 2 -->

Alias for equalsLength

Returns a new array, created by calling function on each element of the given array. For example,

Params

  • array {Array}
  • fn {Function}
  • returns {String}

Example

<!-- array: ['a', 'b', 'c'], and "double" is a
fictitious function that duplicates letters -->
{{map array double}}
<!-- results in: '["aa", "bb", "cc"]' -->

Map over the given object or array or objects and create an array of values from the given prop. Dot-notation may be used (as a string) to get nested properties.

Params

  • collection {Array|Object}
  • prop {Function}
  • returns {String}

Example

// {{pluck items "data.title"}}
<!-- results in: '["aa", "bb", "cc"]' -->

Reverse the elements in an array, or the characters in a string.

Params

  • value {Array|String}
  • returns {Array|String}: Returns the reversed string or array.

Example

<!-- value: 'abcd' -->
{{reverse value}}
<!-- results in: 'dcba' -->
<!-- value: ['a', 'b', 'c', 'd'] -->
{{reverse value}}
<!-- results in: ['d', 'c', 'b', 'a'] -->

Block helper that returns the block if the callback returns true for some value in the given array.

Params

  • array {Array}
  • iter {Function}: Iteratee
  • {Options}: Handlebars provided options object
  • returns {String}

Example

<!-- array: [1, 'b', 3] -->
{{#some array isString}}
  Render me if the array has a string.
{{else}}
  Render me if it doesn't.
{{/some}}
<!-- results in: 'Render me if the array has a string.' -->

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

<!-- array: ['b', 'a', 'c'] -->
{{sort array}}
<!-- results in: '["a", "b", "c"]' -->

Sort an 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.
  • props {String|Function}: One or more properties to sort by, or sorting functions to use.

Example

<!-- array: [{a: 'zzz'}, {a: 'aaa'}] -->
{{sortBy array "a"}}
<!-- results in: '[{"a":"aaa"}, {"a":"zzz"}]' -->

Use the items in the array after the specified index as context inside a block. Opposite of withBefore.

Params

  • array {Array}
  • idx {Number}
  • options {Object}
  • returns {Array}

Example

<!-- array: ['a', 'b', 'c', 'd', 'e'] -->
{{#withAfter array 3}}
  {{this}}
{{/withAfter}}
<!-- results in: "de" -->

Use the items in the array before the specified index as context inside a block. Opposite of withAfter.

Params

  • array {Array}
  • idx {Number}
  • options {Object}
  • returns {Array}

Example

<!-- array: ['a', 'b', 'c', 'd', 'e'] -->
{{#withBefore array 3}}
  {{this}}
{{/withBefore}}
<!-- results in: 'ab' -->

Use the first item in a collection inside a handlebars block expression. Opposite of withLast.

Params

  • array {Array}
  • idx {Number}
  • options {Object}
  • returns {String}

Example

<!-- array: ['a', 'b', 'c'] -->
{{#withFirst array}}
  {{this}}
{{/withFirst}}
<!-- results in: 'a' -->

Block helper that groups array elements by given group size.

Params

  • array {Array}: The array to iterate over
  • size {Number}: The desired length of each array "group"
  • options {Object}: Handlebars options
  • returns {String}

Example

<!-- array: ['a','b','c','d','e','f','g','h'] -->
{{#withGroup array 4}}
  {{#each this}}
    {{.}}
  {{each}}
  <br>
{{/withGroup}}
<!-- results in: -->
<!-- 'a','b','c','d'<br> -->
<!-- 'e','f','g','h'<br> -->

Use the last item or n items in an array as context inside a block. Opposite of withFirst.

Params

  • array {Array}
  • idx {Number}: The starting index.
  • options {Object}
  • returns {String}

Example

<!-- array: ['a', 'b', 'c'] -->
{{#withLast array}}
  {{this}}
{{/withLast}}
<!-- results in: 'c' -->

Block helper that sorts a collection and exposes the sorted collection as context inside the block.

Params

  • array {Array}
  • prop {String}
  • options {Object}: Specify reverse="true" to reverse the array.
  • returns {String}

Example

<!-- array: ['b', 'a', 'c'] -->
{{#withSort array}}{{this}}{{/withSort}}
<!-- results in: 'abc' -->

Block helper that return an array with all duplicate values removed. Best used along with a each helper.

Params

  • array {Array}
  • options {Object}
  • returns {Array}

Example

<!-- array: ['a', 'a', 'c', 'b', 'e', 'e'] -->
{{#each (unique array)}}{{.}}{{/each}}
<!-- results in: 'acbe' -->

code

Embed code from an external file as preformatted text.

Params

  • filepath {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'}}
<!-- optionally specify the language to use -->
{{embed 'path/to/file.hbs' 'html')}}

Embed a GitHub Gist using only the id of the Gist

Params

  • id {String}
  • returns {String}

Example

{{gist "12345"}}

Generate the HTML for a jsFiddle link with the given params

Params

  • params {Object}
  • returns {String}

Example

{{jsfiddle id="0dfk10ks" tabs="true"}}

collection

Inline, subexpression, or block helper that returns true (or the block) if the given collection is empty, or false (or the inverse block, if supplied) if the colleciton is not empty.

Params

  • collection {Object}
  • options {Object}
  • returns {String}

Example

<!-- array: [] -->
{{#isEmpty array}}AAA{{else}}BBB{{/isEmpty}}
<!-- results in: 'AAA' -->

<!-- array: [] -->
{{isEmpty array}}
<!-- results in: true -->

Block helper that iterates over an array or object. If an array is given, .forEach is called, or if an object is given, .forOwn is called, otherwise the inverse block is returned.

Params

  • collection {Object|Array}: The collection to iterate over
  • options {Object}
  • returns {String}

comparison

Helper that renders the block if both of the given values are truthy. If an inverse block is specified it will be rendered when falsy. Works as a block helper, inline helper or subexpression.

Params

  • a {any}
  • b {any}
  • options {Object}: Handlebars provided options object
  • returns {String}

Example

<!-- {great: true, magnificent: true} -->
{{#and great magnificent}}A{{else}}B{{/and}}
<!-- results in: 'A' -->

Render a block when a comparison of the first and third arguments returns true. The second argument is the arithemetic operator to use. You may also optionally specify an inverse block to render when falsy.

Params

  • a {}
  • operator {}: The operator to use. Operators must be enclosed in quotes: ">", "=", "<=", and so on.
  • b {}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or if specified the inverse block is rendered if falsey.

Block helper that renders the block if collection has the given value, using strict equality (===) for comparison, otherwise the inverse block is rendered (if specified). If a startIndex is specified and is negative, it is used as the offset from the end of the collection.

Params

  • collection {Array|Object|String}: The collection to iterate over.
  • value {any}: The value to check for.
  • [startIndex=0] {Number}: Optionally define the starting index.
  • options {Object}: Handlebars provided options object.

Example

<!-- array = ['a', 'b', 'c'] -->
{{#contains array "d"}}
  This will not be rendered.
{{else}}
  This will be rendered.
{{/contains}}

Returns the first value that is not undefined, otherwise the "default" value is returned.

Params

  • value {any}
  • defaultValue {any}
  • returns {String}

Block helper that renders a block if a is equal to b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare="" hash argument for the second value.

Params

  • a {String}
  • b {String}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

Block helper that renders a block if a is greater than b.

If an inverse block is specified it will be rendered when falsy. You may optionally use the compare="" hash argument for the second value.

Params

  • a {String}
  • b {String}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

Block helper that renders a block if a is greater than or equal to b.

If an inverse block is specified it will be rendered when falsy. You may optionally use the compare="" hash argument for the second value.

Params

  • a {String}
  • b {String}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

Block helper that renders a block if value has pattern. If an inverse block is specified it will be rendered when falsy.

Params

  • val {any}: The value to check.
  • pattern {any}: The pattern to check for.
  • options {Object}: Handlebars provided options object
  • returns {String}

Returns true if the given value is falsey. Uses the falsey library for comparisons. Please see that library for more information or to report bugs with this helper.

Params

  • val {any}
  • options {Options}
  • returns {Boolean}

Returns true if the given value is truthy. Uses the falsey library for comparisons. Please see that library for more information or to report bugs with this helper.

Params

  • val {any}
  • options {Options}
  • returns {Boolean}

Return true if the given value is an even number.

Params

  • number {Number}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

Example

{{#ifEven value}}
  render A
{{else}}
  render B
{{/ifEven}}

Conditionally renders a block if the remainder is zero when a operand is divided by b. If an inverse block is specified it will be rendered when the remainder is not zero.

Params

  • {}: {Number}
  • {}: {Number}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

Block helper that renders a block if value is an odd number. If an inverse block is specified it will be rendered when falsy.

Params

  • value {Object}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

Example

{{#ifOdd value}}
  render A
{{else}}
  render B
{{/ifOdd}}

Block helper that renders a block if a is equal to b. If an inverse block is specified it will be rendered when falsy. Similar to eq but does not do strict equality.

Params

  • a {any}
  • b {any}
  • options {Object}: Handlebars provided options object
  • returns {String}

Block helper that renders a block if a is not equal to b. If an inverse block is specified it will be rendered when falsy. Similar to unlessEq but does not use strict equality for comparisons.

Params

  • a {String}
  • b {String}
  • options {Object}: Handlebars provided options object
  • returns {String}

Block helper that renders a block if a is less than b.

If an inverse block is specified it will be rendered when falsy. You may optionally use the compare="" hash argument for the second value.

Params

  • context {Object}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

Block helper that renders a block if a is less than or equal to b.

If an inverse block is specified it will be rendered when falsy. You may optionally use the compare="" hash argument for the second value.

Params

  • a {Sring}
  • b {Sring}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

Block helper that renders a block if neither of the given values are truthy. If an inverse block is specified it will be rendered when falsy.

Params

  • a {any}
  • b {any}
  • options {}: Handlebars options object
  • returns {String}: Block, or inverse block if specified and falsey.

Returns true if val is falsey. Works as a block or inline helper.

Params

  • val {String}
  • options {Object}: Handlebars provided options object
  • returns {String}

Block helper that renders a block if any of the given values is truthy. If an inverse block is specified it will be rendered when falsy.

Params

  • arguments {...any}: Variable number of arguments
  • options {Object}: Handlebars options object
  • returns {String}: Block, or inverse block if specified and falsey.

Example

{{#or a b c}}
  If any value is true this will be rendered.
{{/or}}

Block helper that always renders the inverse block unless a is is equal to b.

Params

  • a {String}
  • b {String}
  • options {Object}: Handlebars provided options object
  • returns {String}: Inverse block by default, or block if falsey.

Block helper that always renders the inverse block unless a is is greater than b.

Params

  • a {Object}: The default value
  • b {Object}: The value to compare
  • options {Object}: Handlebars provided options object
  • returns {String}: Inverse block by default, or block if falsey.

Block helper that always renders the inverse block unless a is is less than b.

Params

  • a {Object}: The default value
  • b {Object}: The value to compare
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

Block helper that always renders the inverse block unless a is is greater than or equal to b.

Params

  • a {any}
  • b {any}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

Block helper that always renders the inverse block unless a is is less than or equal to b.

Params

  • a {any}
  • b {any}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

date

Get the current year.

Example

{{year}}
<!-- 2017 -->

Use moment as a helper. See helper-date for more details.

fs

Read a file from the file system. This is useful in composing "include"-style helpers using sub-expressions.

Params

  • filepath {String}
  • returns {String}

Example

{{read "a/b/c.js"}}
{{someHelper (read "a/b/c.md")}}

Return an array of files from the given directory.

Params

  • directory {String}
  • returns {Array}

html

Stringify attributes on the options hash.

Params

  • options {Object}
  • returns {String}

Example

<!-- value = 'bar' -->
<div{{attr foo=value}}></div>
<!-- results in: <div foo="bar"></div>

Add an array of <link> tags. Automatically resolves relative paths to options.assets if passed on the context.

Params

  • list {String|Array}: One or more stylesheet urls.
  • returns {String}

Example

<!-- {stylesheets: ['foo.css', 'bar.css']} -->
{{css stylesheets}}

<!-- results in: -->
<!-- <link type="text/css" rel="stylesheet" href="foo.css"> -->
<!-- <link type="text/css" rel="stylesheet" href="bar.css"> -->

Generate one or more <script></script> tags with paths/urls to javascript or coffeescript files.

Params

  • context {Object}
  • returns {String}

Example

{{js scripts}}

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>"}}
<!-- results in: 'foo' -->

Block helper for creating unordered lists (<ul></ul>)

Params

  • context {Object}
  • options {Object}
  • returns {String}

Block helper for creating ordered lists (<ol></ol>)

Params

  • context {Object}
  • options {Object}
  • returns {String}

Returns a <figure> with a thumbnail linked to a full picture

Params

  • context {Object}: Object with values/attributes to add to the generated elements:
  • context.alt {String}
  • context.src {String}
  • context.width {Number}
  • context.height {Number}
  • returns {String}: HTML <figure> element with image and optional caption/link.

i18n

i18n helper. See button-i18n for a working example.

Params

  • key {String}
  • options {Object}
  • returns {String}

inflection

Returns either the singular or plural inflection of a word based on the given count.

Params

  • count {Number}
  • singular {String}: The singular form
  • plural {String}: The plural form
  • includeCount {String}
  • returns {String}

Example

{{inflect 0 "string" "strings"}}
<!-- "strings" -->
{{inflect 1 "string" "strings"}}
<!-- "string" -->
{{inflect 1 "string" "strings" true}}
<!-- "1 string" -->
{{inflect 2 "string" "strings"}}
<!-- "strings" -->
{{inflect 2 "string" "strings" true}}
<!-- "2 strings" -->

Returns an ordinalized number as a string.

Params

  • val {String}: The value to ordinalize.
  • returns {String}: The ordinalized number

Example

{{ordinalize 1}}
<!-- '1st' -->
{{ordinalize 21}}
<!-- '21st' -->
{{ordinalize 29}}
<!-- '29th' -->
{{ordinalize 22}}
<!-- '22nd' -->

logging

logging-helpers.

markdown

Block helper that converts a string of inline markdown to HTML.

Params

  • context {Object}
  • options {Object}
  • returns {String}

Example

{{#markdown}}
# Foo
{{/markdown}}
<!-- results in: <h1>Foo</h1> -->

Read a markdown file from the file system and inject its contents after converting it to HTML.

Params

  • context {Object}
  • options {Object}
  • returns {String}

Example

{{md "foo/bar.md"}}

match

Returns an array of strings that match the given glob pattern(s). Options may be passed on the options hash or locals.

Params

  • files {Array|String}
  • patterns {Array|String}: One or more glob patterns.
  • locals {Object}
  • options {Object}
  • returns {Array}: Array of matches

Example

{{match (readdir "foo") "*.js"}}
{{match (readdir "foo") (toRegex "\\.js$")}}

Returns true if a filepath contains the given pattern. Options may be passed on the options hash or locals.

Params

  • filepath {String}
  • pattern {String}
  • options {Object}
  • returns {Boolean}

Example

{{isMatch "foo.md" "*.md"}}
<!-- results in: true -->

math

Return the magnitude of a.

Params

  • a {Number}
  • returns {Number}

Return the sum of a plus b.

Params

  • a {Number}
  • b {Number}
  • returns {Number}

Returns the average of all numbers in the given array.

Params

  • array {Array}: Array of numbers to add up.
  • returns {Number}

Example

{{avg "[1, 2, 3, 4, 5]"}}
<!-- results in: '3' -->

Get the Math.ceil() of the given value.

Params

  • value {Number}
  • returns {Number}

Divide a by b

Params

  • a {Number}: numerator
  • b {Number}: denominator

Get the Math.floor() of the given value.

Params

  • value {Number}
  • returns {Number}

Return the difference of a minus b.

Params

  • a {Number}
  • b {Number}

Get the remainder of a division operation.

Params

  • a {Number}
  • b {Number}
  • returns {Number}

Return the product of a times b.

Params

  • a {Number}: factor
  • b {Number}: multiplier
  • returns {Number}

Add a by b.

Params

  • a {Number}: factor
  • b {Number}: multiplier

Generate a random number between two values

Params

  • min {Number}
  • max {Number}
  • returns {String}

Get the remainder when a is divided by b.

Params

  • a {Number}: a
  • b {Number}: b

Round the given number.

Params

  • number {Number}
  • returns {Number}

Return the product of a minus b.

Params

  • a {Number}
  • b {Number}
  • returns {Number}

Returns the sum of all numbers in the given array.

Params

  • array {Array}: Array of numbers to add up.
  • returns {Number}

Example

{{sum "[1, 2, 3, 4, 5]"}}
<!-- results in: '15' -->

Multiply number a by number b.

Params

  • a {Number}: factor
  • b {Number}: multiplier
  • returns {Number}

misc

Return the given value of prop from this.options.

Params

  • prop {String}
  • returns {any}

Example

<!-- context = {options: {a: {b: {c: 'ddd'}}}} -->
{{option "a.b.c"}}
<!-- results => `ddd` -->

Block helper that renders the block without taking any arguments.

Params

  • options {Object}
  • returns {String}

Get the native type of the given value

Params

  • value {any}
  • returns {String}: Returns the type of value.

Example

{{typeOf 1}}
//=> 'number'
{{typeOf "1"}}
//=> 'string'
{{typeOf "foo"}}
//=> 'string'

Block helper that builds the context for the block from the options hash.

Params

  • options {Object}: Handlebars provided options object.

number

Format a number to it's equivalent in bytes. If a string is passed, it's length will be formatted and returned.

Examples:

  • 'foo' => 3 B
  • 13661855 => 13.66 MB
  • 825399 => 825.39 kB
  • 1396 => 1.4 kB

Params

  • number {Number|String}
  • returns {String}

Add commas to numbers

Params

  • num {Number}
  • returns {Number}

Convert a string or number to a formatted phone number.

Params

  • num {Number|String}: The phone number to format, e.g. 8005551212
  • returns {Number}: Formatted phone number: (800) 555-1212

Abbreviate numbers to the given number of precision. This is for general numbers, not size in bytes.

Params

  • number {Number}
  • precision {Number}
  • returns {String}

Returns a string representing the given number in exponential notation.

Params

  • number {Number}
  • fractionDigits {Number}: Optional. An integer specifying the number of digits to use after the decimal point. Defaults to as many digits as necessary to specify the number.
  • returns {Number}

Example

{{toExponential number digits}};

Formats the given number using fixed-point notation.

Params

  • number {Number}
  • digits {Number}: (Optional) The number of digits to appear after the decimal point; this may be a value between 0 and 20. If this argument is omitted, it is treated as 0.
  • returns {String}: A string representing the given number using fixed-point notation.

Example

{{toFixed "1.1234" 2}}
//=> '1.12'

Params

  • number {Number}
  • returns {Number}

Params

  • number {Number}
  • returns {Number}

Returns a string representing the Number object to the specified precision.

Params

  • number {Number}
  • precision {Number}: (Optional) An integer specifying the number of significant digits. If precison is not between 1 and 100 (inclusive), it will be coerced to 0.
  • returns {String}: A string representing a Number object in fixed-point or exponential notation rounded to precision significant digits.

Example

{{toPrecision "1.1234" 2}}
//=> '1.1'

object

Extend the context with the properties of other objects. A shallow merge is performed to avoid mutating the context.

Params

  • objects {Object}: One or more objects to extend.
  • returns {Object}

Block helper that iterates over the properties of an object, exposing each key and value on the context.

Params

  • context {Object}
  • options {Object}
  • returns {String}

Block helper that iterates over the own properties of an object, exposing each key and value on the context.

Params

  • obj {Object}: The object to iterate over.
  • options {Object}
  • returns {String}

Take arguments and, if they are string or number, convert them to a dot-delineated object property path.

Params

  • prop {String|Number}: The property segments to assemble (can be multiple).
  • returns {String}

Use property paths (a.b.c) to get a value or nested value from the context. Works as a regular helper or block helper.

Params

  • prop {String}: The property to get, optionally using dot notation for nested properties.
  • context {Object}: The context object
  • options {Object}: The handlebars options object, if used as a block helper.
  • returns {String}

Use property paths (a.b.c) to get an object from the context. Differs from the get helper in that this helper will return the actual object, including the given property key. Also, this helper does not work as a block helper.

Params

  • prop {String}: The property to get, optionally using dot notation for nested properties.
  • context {Object}: The context object
  • returns {String}

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

Params

  • key {String}
  • context {Object}: The context object.
  • returns {Boolean}

Example

{{hasOwn context key}}

Return true if value is an object.

Params

  • value {String}
  • returns {Boolean}

Example

{{isObject "foo"}}
//=> false

Parses the given string using JSON.parse.

Params

  • string {String}: The string to parse

Example

<!-- string: '{"foo": "bar"}' -->
{{JSONparse string}}
<!-- results in: { foo: 'bar' } -->

Stringify an object using JSON.stringify.

Params

  • obj {Object}: Object to stringify
  • returns {String}

Example

<!-- object: { foo: 'bar' } -->
{{JSONstringify object}}
<!-- results in: '{"foo": "bar"}' -->

Deeply merge the properties of the given objects with the context object.

Params

  • object {Object}: The target object. Pass an empty object to shallow clone.
  • objects {Object}
  • returns {Object}

Pick properties from the context object.

Params

  • properties {Array|String}: One or more properties to pick.
  • context {Object}
  • options {Object}: Handlebars options object.
  • returns {Object}: Returns an object with the picked values. If used as a block helper, the values are passed as context to the inner block. If no values are found, the context is passed to the inverse block.

path

Get the directory path segment from the given filepath.

Params

  • ext {String}
  • returns {String}

Example

{{absolute "docs/toc.md"}}
<!-- results in: 'docs' -->

Get the directory path segment from the given filepath.

Params

  • ext {String}
  • returns {String}

Example

{{dirname "docs/toc.md"}}
<!-- results in: 'docs' -->

Get the relative filepath from a to b.

Params

  • a {String}
  • b {String}
  • returns {String}

Example

{{relative a b}}

Get the file extension from the given filepath.

Params

  • ext {String}
  • returns {String}

Example

{{basename "docs/toc.md"}}
<!-- results in: 'toc.md' -->

Get the "stem" from the given filepath.

Params

  • filepath {String}
  • returns {String}

Example

{{stem "docs/toc.md"}}
<!-- results in: 'toc' -->

Get the file extension from the given filepath.

Params

  • filepath {String}
  • returns {String}

Example

{{extname "docs/toc.md"}}
<!-- results in: '.md' -->

Resolve an absolute path from the given filepath.

Params

  • filepath {String}
  • returns {String}

Example

{{resolve "docs/toc.md"}}
<!-- results in: '/User/dev/docs/toc.md' -->

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"}}
<!-- results in: 'c/d' -->

{{segments "a/b/c/d" "1" "3"}}
<!-- results in: 'b/c/d' -->

{{segments "a/b/c/d" "1" "2"}}
<!-- results in: 'b/c' -->

regex

Convert the given string to a regular expression.

Params

  • str {String}
  • returns {RegExp}

Example

{{toRegex "foo"}}
<!-- results in: /foo/ -->

Returns true if the given str matches the given regex. A regex can be passed on the context, or using the toRegex helper as a subexpression.

Params

  • str {String}
  • returns {RegExp}

Example

{{test "bar" (toRegex "foo")}}
<!-- results in: false -->
{{test "foobar" (toRegex "foo")}}
<!-- results in: true -->
{{test "foobar" (toRegex "^foo$")}}
<!-- results in: false -->

string

Append the specified suffix to the given string.

Params

  • str {String}
  • suffix {String}
  • returns {String}

Example

<!-- given that "item.stem" is "foo" -->
{{append item.stem ".html"}}
<!-- results in:  'foo.html' -->

camelCase the characters in the given string.

Params

  • string {String}: The string to camelcase.
  • returns {String}

Example

{{camelcase "foo bar baz"}};
<!-- results in:  'fooBarBaz' -->

Capitalize the first word in a sentence.

Params

  • str {String}
  • returns {String}

Example

{{capitalize "foo bar baz"}}
<!-- results in:  "Foo bar baz" -->

Capitalize all words in a string.

Params

  • str {String}
  • returns {String}

Example

{{capitalizeAll "foo bar baz"}}
<!-- results in:  "Foo Bar Baz" -->

Center a string using non-breaking spaces

Params

  • str {String}
  • spaces {String}
  • returns {String}

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_"}}
<!-- results in:  'ABC' -->

{{chop "-ABC-"}}
<!-- results in:  'ABC' -->

{{chop " ABC "}}
<!-- results in:  'ABC' -->

dash-case the characters in string. Replaces non-word characters and periods with hyphens.

Params

  • string {String}
  • returns {String}

Example

{{dashcase "a-b-c d_e"}}
<!-- results in:  'a-b-c-d-e' -->

dot.case the characters in string.

Params

  • string {String}
  • returns {String}

Example

{{dotcase "a-b-c d_e"}}
<!-- results in:  'a.b.c.d.e' -->

Lowercase all of the characters in the given string. Alias for lowercase.

Params

  • string {String}
  • returns {String}

Example

{{downcase "aBcDeF"}}
<!-- results in:  'abcdef' -->

Truncates a string to the specified length, and appends it with an elipsis, .

Params

  • str {String}
  • length {Number}: The desired length of the returned string.
  • returns {String}: The truncated string.

Example

{{ellipsis (sanitize "<span>foo bar baz</span>"), 7}}
<!-- results in:  'foo bar…' -->
{{ellipsis "foo bar baz", 7}}
<!-- results in:  'foo bar…' -->

Replace spaces in a string with hyphens.

Params

  • str {String}
  • returns {String}

Example

{{hyphenate "foo bar baz qux"}}
<!-- results in:  "foo-bar-baz-qux" -->

Return true if value is a string.

Params

  • value {String}
  • returns {Boolean}

Example

{{isString "foo"}}
<!-- results in:  'true' -->

Lowercase all characters in the given string.

Params

  • str {String}
  • returns {String}

Example

{{lowercase "Foo BAR baZ"}}
<!-- results in:  'foo bar baz' -->

Return the number of occurrences of substring within the given string.

Params

  • str {String}
  • substring {String}
  • returns {Number}: Number of occurrences

Example

{{occurrences "foo bar foo bar baz" "foo"}}
<!-- results in:  2 -->

PascalCase the characters in string.

Params

  • string {String}
  • returns {String}

Example

{{pascalcase "foo bar baz"}}
<!-- results in:  'FooBarBaz' -->

path/case the characters in string.

Params

  • string {String}
  • returns {String}

Example

{{pathcase "a-b-c d_e"}}
<!-- results in:  'a/b/c/d/e' -->

Replace spaces in the given string with pluses.

Params

  • str {String}: The input string
  • returns {String}: Input string with spaces replaced by plus signs

Example

{{plusify "foo bar baz"}}
<!-- results in:  'foo+bar+baz' -->

Prepends the given string with the specified prefix.

Params

  • str {String}
  • prefix {String}
  • returns {String}

Example

<!-- given that "val" is "bar" -->
{{prepend val "foo-"}}
<!-- results in:  'foo-bar' -->

Render a block without processing mustache templates inside the block.

Params

  • options {Object}
  • returns {String}

Example

{{{{#raw}}}}
{{foo}}
{{{{/raw}}}}
<!-- results in:  '{{foo}}' -->

Remove all occurrences of substring from the given str.

Params

  • str {String}
  • substring {String}
  • returns {String}

Example

{{remove "a b a b a b" "a "}}
<!-- results in:  'b b b' -->

Remove the first occurrence of substring from the given str.

Params

  • str {String}
  • substring {String}
  • returns {String}

Example

{{remove "a b a b a b" "a"}}
<!-- results in:  ' b a b a b' -->

Replace all occurrences of substring a with substring b.

Params

  • str {String}
  • a {String}
  • b {String}
  • returns {String}

Example

{{replace "a b a b a b" "a" "z"}}
<!-- results in:  'z b z b z b' -->

Replace the first occurrence of substring a with substring b.

Params

  • str {String}
  • a {String}
  • b {String}
  • returns {String}

Example

{{replace "a b a b a b" "a" "z"}}
<!-- results in:  'z b a b a b' -->

Reverse a string.

Params

  • str {String}
  • returns {String}

Example

{{reverse "abcde"}}
<!-- results in:  'edcba' -->

Sentence case the given string

Params

  • str {String}
  • returns {String}

Example

{{sentence "hello world. goodbye world."}}
<!-- results in:  'Hello world. Goodbye world.' -->

snake_case the characters in the given string.

Params

  • string {String}
  • returns {String}

Example

{{snakecase "a-b-c d_e"}}
<!-- results in:  'a_b_c_d_e' -->

Split string by the given character.

Params

  • string {String}: The string to split.
  • returns {String} character: Default is an empty string.

Example

{{split "a,b,c" ","}}
<!-- results in:  ['a', 'b', 'c'] -->

Tests whether a string begins with the given prefix.

Params

  • prefix {String}
  • testString {String}
  • options {String}
  • returns {String}

Example

{{#startsWith "Goodbye" "Hello, world!"}}
  Whoops
{{else}}
  Bro, do you even hello world?
{{/startsWith}}

Title case the given string.

Params

  • str {String}
  • returns {String}

Example

{{titleize "this is title case"}}
<!-- results in:  'This Is Title Case' -->

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

Params

  • string {String}: The string to trim.
  • returns {String}

Example

{{trim " ABC "}}
<!-- results in:  'ABC' -->

Removes extraneous whitespace from the beginning of a string.

Params

  • string {String}: The string to trim.
  • returns {String}

Example

{{trim " ABC "}}
<!-- results in:  'ABC ' -->

Removes extraneous whitespace from the end of a string.

Params

  • string {String}: The string to trim.
  • returns {String}

Example

{{trimRight " ABC "}}
<!-- results in:  ' ABC' -->

Truncate a string to the specified length. Also see ellipsis.

Params

  • str {String}
  • limit {Number}: The desired length of the returned string.
  • suffix {String}: Optionally supply a string to use as a suffix to denote when the string has been truncated. Otherwise an ellipsis () will be used.
  • returns {String}: The truncated string.

Example

truncate("foo bar baz", 7);
<!-- results in:  'foo bar' -->
truncate(sanitize("<span>foo bar baz</span>", 7));
<!-- results in:  'foo bar' -->

Truncate a string to have the specified number of words. Also see truncate.

Params

  • str {String}
  • limit {Number}: The desired length of the returned string.
  • suffix {String}: Optionally supply a string to use as a suffix to denote when the string has been truncated.
  • returns {String}: The truncated string.

Example

truncateWords("foo bar baz", 1);
<!-- results in:  'foo…' -->
truncateWords("foo bar baz", 2);
<!-- results in:  'foo bar…' -->
truncateWords("foo bar baz", 3);
<!-- results in:  'foo bar baz' -->

Uppercase all of the characters in the given string. Alias for uppercase.

Params

  • string {String}
  • returns {String}

Example

{{upcase "aBcDeF"}}
<!-- results in:  'ABCDEF' -->

Uppercase all of the characters in the given string. If used as a block helper it will uppercase the entire block. This helper does not support inverse blocks.

Params

  • str {String}: The string to uppercase
  • options {Object}: Handlebars options object
  • returns {String}

Example

{{uppercase "aBcDeF"}}
<!-- results in:  'ABCDEF' -->

url

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character.

Params

  • str {String}: The un-encoded string
  • returns {String}: The endcoded string

Escape the given string by replacing characters with escape sequences. Useful for allowing the string to be used in a URL, etc.

Params

  • str {String}
  • returns {String}: Escaped string.

Decode a Uniform Resource Identifier (URI) component.

Params

  • str {String}
  • returns {String}

Alias for encodeURI.

Alias for decodeURI.

Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.

Params

  • base {String}
  • href {String}
  • returns {String}

Parses a url string into an object.

Params

  • str {String}: URL string
  • returns {String}: Returns stringified JSON

Strip the query string from the given url.

Params

  • url {String}
  • returns {String}: the url without the queryString

Strip protocol from a url. Useful for displaying media that may have an 'http' protocol on secure connections.

Params

  • str {String}
  • returns {String}: the url with http protocol stripped

Example

<!-- url = 'http://foo.bar' -->
{{stripProtocol url}}
<!-- results in: '//foo.bar' -->

Utils

The following utils are exposed on .utils.

Change casing on the given string, optionally passing a delimiter to use between words in the returned string.

Params

  • string {String}: The string to change.
  • returns {String}

Example

utils.changecase('fooBarBaz');
//=> 'foo bar baz'

utils.changecase('fooBarBaz' '-');
//=> 'foo-bar-baz'

Generate a random number

Params

  • min {Number}
  • max {Number}
  • returns {Number}

History

v0.10.0 - 2017-11-17

changes

  • adds unique to array helpers
  • updates css helper to ensure that path.join() is not called on an absolute URL.

v0.9.0 - 2017-07-03

changes

  • all unit tests now use assert instead of should
  • remove fileSize helper in favor of new bytes helper, which does the same thing, but returns B instead of byte or bytes.
  • JSONParse helper is no longer a block helper. It now returns an object, which can be used as a subexpression to achieve the same behavior as before.
  • adds better error handling for path helpers, since node.js errors are terrible. We have a better way to handle errors that will be implemented in a near future release.
  • adds inline helper support to isEmpty, so it can now be used as an inline or block helper
  • adds raw helper
  • adds regex helpers
  • adds inline helper support to most of the comparison helpers, so they can now be used as inline or block helpers
  • adds pluck helper to array helpers
  • adds prepend and append helpers to string helpers
  • adds isTruthy and isFalsey comparison helpers
  • adds escape and url_encode and url_decode URL helpers
  • adds attr helper to html helpers
  • adds year helper to date helpers
  • adds typeOf and frame helpers to misc helpers
  • adds abs, minus, modulo, plus, times to math helpers
  • moves ellipsis helper from html helpers to string helpers
  • moves truncate helper from html helpers to string helpers
  • moves reverse helper from string helpers to array helpers
  • differentiate eq and is helpers so that eq is strict equality and is is not
  • removes mm helper, use match instead

v0.8.4 - 2017-07-03

changes

  • removes strlen helper in favor of fixing the length helper

v0.8.3 - 2017-07-03

changes

  • adds strlen helper
  • adds itemAt helper
  • clean up code comments for array helpers

v0.8.2 - 2017-03-30

changes

  • documentation updates
  • fixes md helper to use sync by default

v0.8.1 - 2017-03-30

changes

  • fixes sorting in withSort helper. see #245
  • adds toPath helper
  • handle null inputs in number helpers
  • adds stripProtocol helper

v0.8.0 - 2017-01-25

changes

  • handle string arguments in list helpers
  • adds JSONParse helper as an alias for parseJSON

v0.7.6 - 2017-01-08

changes

  • fixes markdown helpers. see #226
  • documentation improvements and other minor fixes

v0.7.0 - 2016-07-16

changes

  • The or helper can now take a variable number of arguments

v0.6.0 - 2016-05-13

changes

  • the main export is now a function that takes a name or array of names of helper types to load. Example helpers(['string', 'array']) will load only the string and array helpers
  • helper types can alternatively be accessed as methods. example - helpers.path() will return all of the path helpers.
  • handlebars may be provided by the user. if not provided it will fall back to the handlebars-helpers handlebars
  • helpers are now as generic as possible, with little to no code related to assemble, grunt, etc.
  • helpers are lazy-loaded using getters for improved performance
  • Once tests are added for the md and markdown helpers, we'll have 100% unit test coverage on helpers

v0.3.3 - 2013-09-03

changes

  • Adds fileSize helper.
  • Adds startsWith helper.

v0.3.2 - 2013-08-20

changes

  • Adds glob helper.

v0.3.0 - 2013-07-30

changes

  • The project has been refactored, cleaned up, and full documentation has bee put up at http://assemble.io

v0.2.4 - 2013-05-11

changes

  • Adding object globbing utility functions to be used in helpers later.

v0.2.3 - 2013-05-11

changes

  • File globbing added to some helpers. Including md and some file helpers.

v0.2.0 - 2013-05-07

changes

  • A bunch of new tests for markdown and special helpers.
  • Refactored most of the rest of the helpers to separate functions from Handlebars registration.

v0.1.32 - 2013-05-02

changes

  • Updates utils and a number of helpers, including value, property, and stringify.

v0.1.31 - 2013-04-21

changes

  • Fixes relative helper

v0.1.30 - 2013-04-20

changes

  • Refactoring helpers-collection module to separate the functions from the Handlebars helper registration process.

v0.1.25 - 2013-04-16

changes

  • Adding defineSection and renderSection helpers to try to get sections populated in a layout from the page.

v0.1.21 - 2013-04-07

changes

  • Add markdown helpers back, add more tests.

v0.1.20 - 2013-04-06

changes

  • Generalized helpers structure, externalized utilities.

v0.1.11 - 2013-04-05

changes

  • New authors and gist helpers, general cleanup and new tests.

v0.1.10 - 2013-04-04

changes

  • Externalized utility javascript from helpers.js

v0.1.8 - 2013-03-28

changes

  • Gruntfile updated with mocha tests for 71 helpers, bug fixes.

v0.1.7 - 2013-03-18

changes

  • New path helper 'relative', for resolving relative path from one absolute path to another.

v0.1.3 - 2013-03-16

changes

  • New helpers, 'formatPhoneNumber' and 'eachProperty'

v0.1.2 - 2013-03-15

changes

  • Update README.md with documentation, examples.

[v0.1.0] - 2013-03-06

changes

  • First commit.

About

Related projects

  • assemble: Get the rocks out of your socks! Assemble makes you fast at creating web projects… more | homepage
  • template-helpers: Generic JavaScript helpers that can be used with any template engine. Handlebars, Lo-Dash, Underscore, or… more | homepage
  • utils: Fast, generic JavaScript/node.js utility functions. | homepage

Contributing

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

Contributors

Release history

Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Running tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test

Author

Brian Woodward

Jon Schlinkert

License

Copyright © 2017, Jon Schlinkert. When this project was created some helpers were sourced from Swag, by Elving Rodriguez. Released under the MIT License.


This file was generated by verb-generate-readme, v0.6.0, on November 17, 2017.

handlebars-helpers's People

Contributors

alesk avatar alisd23 avatar arkkimaagi avatar backflip avatar brendaniel avatar cfjedimaster avatar dandv avatar denspirit avatar doowb avatar greenraccoon23 avatar hariadi avatar huntie avatar iamstolis avatar jasonbellamy avatar jfroom avatar joeybaker avatar jonschlinkert avatar jtsuyuki avatar kevindavus avatar laurentgoderre avatar makotot avatar melindrea avatar nlfurniss avatar robsilva avatar sheedy avatar stephenway avatar thegreatsunra avatar twipped avatar why2pac avatar xymbol avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

handlebars-helpers's Issues

namespacing

rename generic helpers to avoid collisions with local variables.

helper: basename

basename

Returns the basename of a given file.

Usage:

Use {{basename}} to return the name of the current file.

or: {{basename "docs/toc.md"}}

or: {{basename [variable]}}

{{link}} tag causes an error

I just ran npm update on my project that was working just fine before and this problem popped to my sights.

The problem

If I have a tag named {{link}} in my handlebars code,


---
link: http://www.google.com

---
Check this out: {{link}}

Assemble throws an error:

File "index.html" assembled...ERROR
Warning: Cannot read property 'hash' of undefined Use --force to continue.

Aborted due to warnings.

If I rename this variable to something else, the compiling works just fine. I installed a clean version of assemble with grunt-init and tested by just adding the {{link}} tag to the index.hbs file.

The cause

I was able to pinpoint the line that throws this error to here:
https://github.com/assemble/handlebars-helpers/blob/master/lib/utils/utils.js#L87

This is the code on that line:

return value === 'undefined' || Utils.toString.call(value) === '[object Function]' || (value.hash != null);

And sure enough, value is undefined. I did not do a pull request related to this, as the fix looks trivial to this row. (checking if value exists before trying to access it.) But the real problem lies elsewhere.


The deeper cause

Apparently the {{link}} has been added as an helper since I last updated handlebars-helpers. Digging up why this error happened was a real pain since the error message is quite unclear. It took me a while to figure out that the {{link}} tag was the problem and a while after that to realize that there's a helper called link now. So, the problem is with the link helper. We could (and should) fix it there too. However, I think the root of the problem lies even deeper and here is a chance to talk about it.


The deeper deeper cause

Currently we have all these things in the same namespace:

  • handlebars internals (like #if)
  • handlebars-helpers (like link)
  • assemble provided variables like (pages, page...)
  • variables from grunt assemble configuration
  • user defined variables
  • user defined helpers

While the first three sources for variable names would stay in balance with each other, addition, the last three come from the user. Adding new features to any of the three first potentially breaks users variables and helpers silently. This is not a good thing.

Solution

I'd suggest that we'd have some sort of an system to handle these name collision situations and a system to avoid them. Here are my three ideas for this matter:

Idea 1

So, at first there should be a way to throw error about a variable being used as a helper when I try to define it in the frontmatter or yaml file. Also the error report about some helper failing should be way better. Maybe a try catch block around helper code somehow?

Idea 2

Then I'd recommend some sort of an way to namespace helpers, maybe with something like: Instead of naming helpers randomly, naming them instead of link to be $link or something similar. This way the helpers would not collide with user variables. I know that this is a radical change, but as the helpers library grows, more collisions will happen with already built projects and renaming variables on a single page is annoying, but doing them whole project wide, it's a pain. An alternative to this is to recommend for the user to use some naming scheme that assemble will avoid using in it's system. But that puts the load on user instead of keeping it with the tool that tries to make stuff easier for the user.

Idea 3

As a third recommendation I'd like to have a way to enable/disable builtin helpers from the grunt file. This would let the users add their modified helpers if need be to their assemble projects with same name, or fix problems that happen on namespace collisions. Maybe a configuration to blacklist/whitelist helpers would be nice. So that I could choose if I want to remove some of the builtin helpers with a blacklist and keep all the rest (and future upcoming ones), or if I want to include only select few helpers by whitelisting them and ignore all the rest (even future ones).

namespacing

From @Arkkimaagi on issue #33


"If the built in helpers would be found from under the _, would be a great start. The bare minimum that should be done is to help the users with collisions.

  • Better error messages (maybe that helper utility library that handles it automatically)
  • Lets check if we can detect collisions automatically and warn about them too.
  • How about listing all the variables that will be on the page scope and what they do in the docs under section "Avoiding variable name collisions" etc.

I'm thinking about a list to instruct the users about avoiding collisions using a list much like I have above. Maybe with documentation on what does what and why. Possibly a short code comment after each section and a whole paragraph after that about good guidelines to keep in mind."

helper: gist

gist

Embed Gists

  • {{ gist 519323 }}
  • {{ gist 5193239 file1.md }}

Embed public GitHub Gists by adding only the Id of the Gist. The helper also accepts an optional second parameter for targeting a specific file on the Gist.

Parameters: String|String (optional)
Default: undefined
Syntax: {{ gist [id] [filename] }}

Example:

{{ gist 5193239 }}

You can pass in a file name as a second parameter if you need to embed multiple files from the same Gist, like this:

{{ gist 5193239 file1.md }}
{{ gist 5193239 file2.md }}
{{ gist 5193239 file3.md }}

helper: {{ include }}

Works like partials, but allows you to use variables:

---
layout: default.hbs
title: Some Page Title
content: ../path/to/my_content.md

---

{{{ include content }}}

{{{ include "some-partial.md" }}}

and it would be great to be able to pass in an optional third parameter for data to override the default data that would be used for a template: {{{ include [partial] [data] }}}

{{{ include "some-other-partial.hbs" "path/to/data.json" }}}

eachProperty does not work properly

First of all, the documentation on the README.md says that one can use the eachProperty like this:

{{#eachProperty object}}
    {{property}}: {{value}}<br/>
{{/eachProperty }}

(The documentation on this part seems to be under construction, as some parts of it are totally missing.)

While in the code it's returned like this:

result += options.fn({
  key: key,
  value: value
});

Which means that the documentation should be updated to:

{{#eachProperty object}}
    {{key}}: {{value}}<br/>
{{/eachProperty}}

Or the returning thing should be changed to "property" like in the docs.

The code however still does not work, as whenever I try to use {{value}} inside handlebars code, I get this error:

Warning: Unable to read "[object Object]" file (Error code: ENOENT). Use --force to continue.

If I access the same variable by {{lowercase value}} it works as expected.

I tried to find colliding helpers and such, but I was unable to do so.

label helpers to indicate how they should be sorted

once we implement a system for wrapping the helpers, most of the helpers in the lib will work with any env right out of the box. however, some of them won't. A small handful of the helpers are pretty much hard-coded to either node.js, assemble or grunt.

We need to get those helpers sorted out or labeled somehow so we can automate the process for wrapping all the helpers at once

eachIndex should work with Objects too

The actual doc mentions the following:

Current implementation of the default Handlebars loop helper {{#each}} adding index (0-based index) to the loop context.

Which is not totally true, as eachIndex adds the index only for arrays, not objects.

This will work:

var data = [
  { title: "…", description: "…" },
  { title: "…", description: "…" },
  { title: "…", description: "…" }
}

{{#eachIndex data}}
  <h2>{{index}}: {{title}}</h2>
{{/eachIndex}}

This will not work:

var data = {
  firstItem: { title: "…", description: "…" },
  secondItem: { title: "…", description: "…" },
  thirdItem: { title: "…", description: "…" }
}

{{#eachIndex data}}
  <h2>{{index}}: {{title}}</h2>
{{/eachIndex}}

Maybe there is an existing solution to achieve this without altering the data source.

formatDate formats timezone incorrectly

I tried to dig to the original library, but it is gone and links mentioned in docs nolonger work.

This helper is a port of the formatDate-js library by Michael Baldry.

if I render time with moment.js like this:

moment().format("ddd, DD MMM YYYY HH:mm:ss ZZ")

I get:

Sat, 29 Jun 2013 23:40:08 +0300

If I render with formatDate I get with this:

---
lastBuildDate: <%= new Date() %>

---
{{formatDate lastBuildDate "%a, %d %b %Y %H:%M:%S %z"}}

this result:

Sat, 29 Jun 2013 23:40:08 +0003

Notice how 3 hour timezone has changed to 3 minute timezone? Not good. 👎

What if we'd use moment.js instead and get bunch more options with it? Sure, the old formattings would break, but..

How can I use it without node

Hi, thanks for this awesome collection of helpers.

I'm doing a project in Django, I use Backbone.js inside of the project and my javascript template renderer is Handlebars.

I need to use this helpers importing them with require.js but I don't know the way to do it, can you guide me please?

"Seamlessly" utilizing helper-lib in Assemble

It appears that the documentation to utilize helper-lib within Assemble is out of date since the repository shift. I'd be happy to write up the documentation, but could use some direction.

I've installed "helper-lib" via npm.

npm install helper-lib --save-dev

I then added the following line within my Gruntfile.js file.

grunt.loadNpmTasks('helper-lib');

Lastly I updated my assemble task to include the helper.

assemble: {
            options: {
                engine: 'handlebars',
                helpers: ['helper-lib', 'node_modules/assemble/lib/engines/handlebars/helpers/defaultHelpers'],
                flatten: true,
                data: 'src/data/*.json',
                partials: [ 'src/partials/**/*.hbs' ],
                assets: 'examples/assets',
                version: '<%= pkg.version %>'
            },
            ...
}

When I run any command via Grunt, I get the following error:

>> Local Npm module "helper-lib" not found. Is it installed?

When I look in node_modules I see node_modules/helper-lib, so I'm not sure what gives. If someone can give me some direction I'll make some documentation updates.

Suggestion: valueIn helper

How about an inverse of the {{inArray}} helper? Something that would work like the example docs below.

If there's enough interest in this I'd be glad to submit a pull request and make it so. If I do so, which section should it go into? (Collections?)


{{valueIn}}

Conditionally render a block if the value is in a specified collection.
Parameters: value string|int - One or more values to test against. (Required), [...]

Data:

"value": "Fry"

Template:

{{#valueIn value "Professor Farnsworth" "Fry" "Bender"}}
  I'm walking on sunshine!
{{else}}
  I'm walking on darkness.
{{/valueIn}}

Renders to:

I'm walking on sunshine!

withSort does not support descending

Hi,

I'm using withSort and trying to sort by a property 'year'. But I can't choose to sort in descending order. Is there functionality to do this? Or is this something I should be adding as a custom helper?

Thanks,
Andi

"usemin" helper

Every time I see grunt usemin in a project it makes me cringe. This would be so much easier to do with Assemble and helpers.

Get page variable in nested block helpers

Someone discovered an issue with the i18n task that I'm trying to resolve. Given the current code:

{{#prettify}}
  {{#i18n "key"}}{{/i18n}}
{{/prettify}}

The i18n fails because it no longer sees the language parameter of the page. I'm wondering, how do I get access to the page regardless of where the block is.

helper: filename

filename

Returns the file name of a given file, including basename and extension. By default the template only requires the {{filename}} expression

An optional second parameter can be passed

Usage:

{{filename "docs/toc.md"}}

Returns:

toc.md

Of course, this probably seems useless, but when variables are used instead it would be more valuable:

{{filename snippet}}

Generalizing code for helpers

If you are familiar with Assemble and you're reading this, then you know that we have obviously renamed "helper-lib" to handlebars-helpers.

We are not really changing anything about how helpers work with Assemble, but we will be making material changes to how helpers are packaged and organized. We will:

  • Externalize some of the utility code to a new lib/repo, probably assemble-utils
  • Organize and reduce any external dependencies
  • Add logging and error reporting to that library
  • Externalize the functions for the helpers in this repo to another repo, and then just require them back into this repo, so it might not even have a noticeable impact to current users of this lib. The reason for doing this is...
  • In the lodash-mixins repo we will require in the same functions as the handlebars helpers, which makes it more flexible so you can use either handlebars helpers or lodash mixins with the same helper methods wherever you need them.

This refactoring should also allow us to easily "templatize" the process of adding new helpers and mixins, ensuring that they are automatically added when new helper methods are added.

This "generalization" will only work with some helpers, mostly likely the helpers that can and should be generalized this way, and it also makes it clear which helpers shouldn't be included in the main libs. Any helpers that can't be generalized this way or don't seem like a good fit for the general lib will be isolated and externalized into individual repos so that they can be consumed via options: { helpers: '**/helper-*.js' }

We will add some examples and conventions for adding custom helpers to the Custom Helpers page in the documentation.

helper: blockquote

blockquote

Create a blockquote

Outputs a string with a given attribution as a quote.

{{#blockquote "doowb" "http://github.com/quote/source" "This is the title" }}
  This is your quote.
{{/blockquote}}

results in:

<blockquote>
  <p>This is your quote.</p>
  <footer> 
    <strong>`doowb</strong>
    <cite> 
      <a href="http://github.com/quote/source">This is the title</a>
    </cite>
  </footer>
</blockquote>

embed helper: {{ embed [filename] [syntax] }}

embed

For embedding code snippets by referencing an external file.

Embed code snippets from any file/accepted file types with the embed variable. You can also pass in a second parameter to force syntax highlighting for a specific language.

Parameters: String|String (optional)
Default: undefined
Syntax: {{ embed [filename] [syntax] }}

Example:

{{ embed 'src/test.json' }}

Forced highlighting: in this example highlighting is forced as javascript instead of json.

{{ embed 'src/test.json' 'javascript' }}

eachIndex+1?

How about a eachIndex helper that has 1 based indexing instead of 0 based?

Generating a navigation with dynamic active class

I'm trying to generate a navigation with a dynamic active class & here is my YAML & Handelbars

config.yaml


---
mainnav:
- home
- about us
- contact

---

menu.hbs partial

{{#config.mainnav}}
      <li><a {{#is page.basename this}} class="is-current" {{/is}} href="{{hyphenate this}}.html">{{capitalizeEach this}}</a></li>
{{/config.mainnav}}

everything is working but the active class, it doesn't get applied at all.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.