nymag-handlebars
A collection of helpers and partials for handlebars
Installation
npm install --save nymag-handlebars
Usage
By default, nymag-handlebars
will export a function that returns a new handlebars instance with all of the helpers and partials added.
var hbs = require('nymag-handlebars')(),
template = hbs.compile('<h1>Hello {{ place }}!</h1>'),
result = template({ place: 'World' });
Passing env in
If you want to configure and use your own handlebars environment, you can pass it through
var Handlebars = require('express-handlebars'),
env = new Handlebars({ }),
hbs = require('nymag-handlebars')(env),
app = require('express')();
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
Helpers
Currently 56 helpers in 10 categories:
arrays
components
conditionals
html
misc
numbers
objects
strings
time
urls
arrays
join all elements of array into a string, optionally using a given separator
Params
array
(array)[sep]
(string) the separator to use (defaults to ', ')
Returns (string)
Example
{{ join ["a", "b", "c"] "-" }}
//=> "a-b-c"
map through array, call function on each item
Params
array
(array|string) of items to iterate throughfn
(function) to run on each item
Returns (array)
Example
{{ join (map [{ a: "1" }, { a: "2" }] (getProp "a")) }}
//=> "1, 2"
return an array of numbers, in order
note: can be used inline or as a block helper (will iterate through all numbers)
Params
[start]
(number) on this number (defaults to 0)end
(number) on this number[options]
(object)
Returns (array)
Example
{{#range 1 5}}{{ this }}{{/range}}
//=> 1234
components
addAnnotatedTextAria ( code | tests )
Add aria to phrases in paragraphs, corresponds to annotation ids.
Params
content
(array) list of components
Returns (array) content
Example
{{> component-list (addAnnotatedTextAria content)}}
addInSplashAds ( code | tests )
Add in article ads to list of components in an article
Params
content
(array) the list of components in the articlearticleData
(object) the entire article's data, used to pull in the different ad units definedafterComponent
(string) the component type to insert the ad after
Returns (object) splash
Example
{{> component-list (addInSplashAds content this "picks-links-container") }}
addOrderedIds ( code | tests )
Add ordered ids to components within a componentlist
Params
content
(Array) list of componentsprefix
(string) prefix for the ids[offset]
(number) index to start at, defaults to 1
Returns (Array) content
Example
{{> component-list (addOrderedIds content "annotation-") }}
adsToDummies ( code | tests )
Given a list of component instance objects, replace each ad component
with a site's "dummy" ad instance, matching the properties of the ad
instance replaced.
Params
content
(Array) an array of component instance objects,
e.g. [{_ref: 'a/uri/etc', foo: 'bar'}, ...]
[dummyAd]
(Object) an ad object with the reference to the dummy ad instance
Returns (Array) an array of components, with ads replaced with the
ad dummy instance
displaySelf ( code | tests )
Return the first component (from a list of components) with a truthy displaySelf
property. Used by Spaces.
Params
components
(array) with displaySelf
properties
Returns (object) first component with displaySelf: true
Example
{{> component-list (displaySelf content) }}
displaySelfAll ( code | tests )
Return all components (from a list of components) with a truthy displaySelf
property. Used by Spaces.
Params
components
(array) with displaySelf
properties
Returns (array) all components with displaySelf: true
Example
{{> component-list (displaySelfAll content) }}
getComponentName ( code | tests )
get a component's name from the reference
Params
ref
(string) full component uri
Returns (string)
Example
{{ getComponentName "domain.com/components/foo" }}
//=> foo
conditionals
compare two values, with an operator.
note: if you don't pass an operator, it assumes ===
note: this can be used as a block or inline helper
Params
left
(*) left valueoperator
(string) to compare withright
(*) right value[options]
(object)
Returns (string) if inline, otherwise calls block functions
Example
{{ compare 10 ">" 5 }}
//=> "true"
overwrite default handlebars 'if' helper
this adds support for an inline helper, {{if foo bar}}
(if foo is truthy, print bar)
as well as an inline if/else helper, {{if foo bar else=baz}}
(if foo is truthy, print bar. otherwise, print baz)
Params
conditional
(*) to check for truthinessvalue
(*) to print if conditional is truthy[options]
(object)
Returns (string) if inline, otherwise calls block functions
Example
{{ if true "bar" else="baz" }}
//=> "bar"
block helper for checking if ALL arguments passed in are truthy
Returns (string) calls block functions
Example
{{#ifAll foo bar baz}}
all are truthy
{{else}}
not all are truthy
{{/ifAll}}
block helper for checking if ANY arguments passed in are truthy
Returns (string) calls block functions
Example
{{#ifAny foo bar baz}}
at least one is truthy
{{else}}
none are truthy
{{/ifAny}}
block helper for checking if NO arguments passed in are truthy
Returns (string) calls block functions
Example
{{#ifNone foo bar baz}}
all are falsy
{{else}}
not all are falsy
{{/ifNone}}
compare the modulo of two values to a third value
Params
dividend
(number)divisor
(number)remainder
(number)[options]
(object)
Returns (string) if inline, otherwise calls block functions
Example
{{modulo 3 2 1}}
//=> true
block helper for checking that NOT ALL arguments passed in are truthy
note: this is the inverse of the ifAll helper
Returns (string) calls block functions
Example
{{#unlessAll foo bar baz}}
not all are truthy
{{else}}
all are truthy
{{/ifAll}}
html
perWordClasses ( code | tests )
wraps each word in spans with classes allowing designers and devs to target individual words with css
Params
html
(string) to add classes tooptions
(object)[options.hash.perLetter]
(boolean) if you want an extra span wrapping each letter. defaults to true
Returns (string) words wrapped in classes
Example
{{{ perWordClasses "One two three" perLetter=false }}}
//=> <span class="_one">One</span> <span class="_two">two</span> <span class="_three">three</span>
striptags ( code | no tests )
straight passthrough to striptags
Example
{{ striptags "<p><b>Hello</b> <em>World!</em></p>" }}
//=> Hello World!
counts the words in a string of text or html
Params
Returns (number) the number of words
Example
{{wordCount "<div> This is <b> cool </b> </div>"}}
//=> 3
misc
return the first value if it's not empty, otherwise return the second value
note: this overrides handlebar-helper's default helper, since that only checks for null values (not all falsy/empty values)
Params
value
(*) to checkdefaultValue
(*) value to return if first value is falsy
Example
{{ default "" "foo" }}
//=> foo
Extract the height of a mediaplay image given the image URL.
Params
Returns (object) extracted height
Example
{{ extractImgHeight feedImgUrl }}
//=> 946
Extract the width of a mediaplay image given the image URL.
Params
Returns (Object) extracted width
Example
{{ extractImgWidth feedImgUrl }}
//=> 1420
get the index of something inside something else
Params
outside
(*) array, string, etc (anything with indexOf
)inside
(*) anything that can exist inside something else
Returns (number)
Example
{{ indexOf "foo" "o" }}
//=> 1
set data into current context or other optional context/object
note: doesn't return anything
Params
[obj]
(object) context or object for storing data beyond current contextkey
(string) _set()
key/pathval
(*) value to set
Example
{{ set "a.b.c" "abc" }}{{ a.b.c }}
//=> "abc"
slugToSiteName ( code | tests )
return comma-separated site names from comma-separated slugs
Params
slugs
(string) comma-separated string of slugs
Returns (string)
Example
{{ slugToSiteName (commaSeparated crosspost) }}
numbers
Return the product of a
plus b
Params
Returns (number)
Example
{{ add 3 2 }}
//=> 5
add commas to numbers.
note: this overrides handlebars-helpers' addCommas
helper because we want to preserve zeroes in decimals (for money)
e.g. 1234.50
→ 1,234.50
instead of 1,234.5
note: decimals are only preserved if passed in as a string (they don't exist in js numbers)
Params
Returns (string)
Example
{{ addCommas "1234.50" }}
//=> "1,234.50"
addOrdinalSuffix ( code | tests )
add ordinal after a number
e.g. 1
→ 1st
, 2
→ 2nd
, 3
→ 3rd
Params
i
(number|string) number to add ordinal after
Returns (string)
Example
{{ addOrdinalSuffix 1 }}
//=> 1st
Return the result of a
divided by b
Params
Returns (number)
Example
{{ divide 100 4 }}
//=> 25
Return the product of a
multiplied by b
Params
Returns (number)
Example
{{ multiply 10 10 }}
//=> 100
converts things (usually strings) into numbers
note: this is useful if you need to parse user input
Params
x
(number|string) thing to convert into a number
Returns (string)
Example
{{ num "123" }}
//=> 123
Returns a number within a specified range.
Params
Returns (Number)
Return the rounded value of x
, optionally always rounding up or down
Params
x
(number|string)[direction]
(string) always round x
up or down, expects values 'up' or 'down', otherwise just round
Returns (number)
Example
{{ round 1.5 "down" }}
//=> 1
Return the product of a
minus b
Params
Returns (number)
Example
{{ subtract 3 2 }}
//=> 1
format thousands using k
e.g. 1000
→ 1k
Params
x
(number|string) number to format
Returns (string)
Example
{{ toK 1234.5 }}
//=> "1.2k"
objects
commaSeparated ( code | tests )
Turn an object into a comma-delineated list of key names, depending if their values are true/false
Params
obj
(object)shouldCapitalize
(boolean) capitalizes first word in each key
Returns (string)
Example
{{ commaSeparated {alpha: true, "bravo charlie": true} true }}
//=> "Alpha, Bravo charlie"
get property in object
this is similar to handlebars-helpers' get
, but the context is called on a returned function.
this allows you to easily convert arrays of objects to arrays of a specific property from each objects
Params
prop
(string) key/path, passed to _get()
Returns value of the property from the object
Example
{{ join (map [{ a: "1" }, { a: "2" }] (getProp "a"))}}
//=> "1, 2"
stringify JSON
note: doesn't blow up on circular references
Params
Returns (string)
Example
{{{ stringify { a: "b" } }}}
//=> "{"a":"b"}"
strings
capitalize the first character in a string
Params
Returns (string)
Example
{{ capitalize "foo bar" }}
//=> "Foo bar"
capitalizeAll ( code | tests )
capitalize every word in a string
Params
Returns (string)
Example
{{ capitalizeAll "foo bar" }}
//=> "Foo Bar"
concatenate any number of strings
Returns (string) concatenated string
Example
{{ concat "Foo" "Bar" "Baz" }}
//=> "FooBarBaz"
check if a substring exist within a string. This is very similiar to the
indexOf helper, except it uses String.prototype.includes() and returns a
boolean.
Params
string
(string)substring
(string)
Returns (boolean)
Example
{{ includes "hello world" "world" }}
//=> true
kebabCase ( code | no tests )
straight passthrough to _kebabCase
Example
{{ kebabCase "Foo Bar Baz" }}
//=> "foo-bar-baz"
longestWord ( code | tests )
returns the number of characters in the longest word of a string. Punctuation is NOT ignored.
Params
str
(string) string to search through
Returns (number) of letters in the longest word
Example
{{ longestWord "Foo Ba b" }}
//=> 3
lower cases a string
note: non-strings will return emptystring
Params
Returns (string) lower cased
Example
{{ lowercase "Foo" }}
//=> "foo"
randomString ( code | tests )
generate a random string
note: by default it generates an 8-character string
Params
[prefix]
(string) string to append random stuff to[options]
(object)[options.hash.characters]
(number) generate string of a custom length
Returns (string)
Example
{{ randomString "greatest-hit-" characters=3 }}
//=> "greatest-hit-z56"
removeSpaces ( code | tests )
remove spaces, used by in-page id
attributes so we can do in-page links
(per the HTML spec IDs cannot have spaces)
Params
Returns (string)
Example
{{ removeSpaces "Foo Bar" }}
//=> "FooBar"
replace all occurrences of a
with b
note: this does simple string replacement, not regex
Params
str
(string) to replace insidea
(string) to replaceb
(string) the replacement
Returns (string)
Example
{{ replace "Foo Bar" "Bar" "Baz" }}
//=> "Foo Baz"
trim leading and trailing whitespace from a string
Params
Returns (string)
Example
{{ trim " Foo " }}
//=> "Foo"
If a string is over a given length, truncate and append an ellipsis character to the end.
Params
str
(string) to shortenlen
(number) desired lengthoptions
(object)[options.hash.suffix]
(string) to append to truncated string, defaulting to an ellipsis
Returns (string)
Example
{{ truncate "Foo Bar" 4 }}
//=> "Foo…"
time
articleDate ( code | tests )
generate article dates and times, based on a relative format
Params
datetime
(Date|string) for date-fns
to parse
Returns (string)
Example
{{ articleDate "Fri, 13 Jan 2017 18:22:16 GMT" }}
//=> "Yesterday at 6:22 p.m."
dateMinimal ( code | tests )
generate display date (without time), based on a relative format
Params
datetime
(Date|string) for date-fns
to parse
Returns (string)
Example
{{ dateMinimal "Fri, 13 Jan 2017 18:22:16 GMT" }}
//=> "Yesterday"
formatLocalDate ( code | tests )
Formats a date with date-fns
Params
date
(*)[format]
(string)
Returns (string)
moment ( code | no tests )
No description
urls
encode urls (ported from the nunjucks urlencode
filter)
note: handlebars-helpers
contains an encodeURI
helper, but it doesn't handle arrays or objects.
Params
Returns (string) urlencoded data
Example
{{ urlencode "&" }}
//=> "%26"
Partials
Currently 1 partial:
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
This project is released under the MIT license.