clayhandlebars
A collection of helpers and partials for handlebars
Installation
npm install --save clayhandlebars
Usage
By default, clayhandlebars
will export a function that returns a new handlebars instance with all of the helpers and partials added.
var hbs = require('clayhandlebars')(),
template = hbs.compile('<h1>Hello {{ place }}!</h1>'),
result = template({ place: 'World' });
// result: <h1>Hello World!</h1>
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({ /* some config */ }),
hbs = require('clayhandlebars')(env),
app = require('express')();
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
Helpers
Currently 57 helpers in 10 categories:
arrays
components
- addAnnotatedTextAria ( code | tests )
- addInSplashAds ( code | tests )
- addOrderedIds ( code | tests )
- adsToDummies ( code | tests )
- displaySelf ( code | tests )
- displaySelfAll ( code | tests )
- filterComponents ( code | tests )
- getComponentName ( code | tests )
conditionals
- compare ( code | tests )
- if ( code | tests )
- ifAll ( code | tests )
- ifAny ( code | tests )
- ifNone ( code | tests )
- modulo ( code | tests )
- unlessAll ( code | tests )
html
misc
- default ( code | tests )
- extractImgHeight ( code | tests )
- extractImgWidth ( code | tests )
- indexOf ( code | tests )
- set ( code | tests )
- slugToSiteName ( code | tests )
numbers
- add ( code | tests )
- addCommas ( code | tests )
- addOrdinalSuffix ( code | tests )
- divide ( code | tests )
- multiply ( code | tests )
- num ( code | tests )
- random ( code | tests )
- round ( code | tests )
- subtract ( code | tests )
- toK ( code | tests )
objects
strings
- capitalize ( code | tests )
- capitalizeAll ( code | tests )
- concat ( code | tests )
- includes ( code | tests )
- kebabCase ( code | no tests )
- longestWord ( code | tests )
- lowercase ( code | tests )
- randomString ( code | tests )
- removeSpaces ( code | tests )
- replace ( code | tests )
- trim ( code | tests )
- truncate ( code | tests )
time
- articleDate ( code | tests )
- dateMinimal ( code | tests )
- formatLocalDate ( code | tests )
- moment ( code | no tests )
urls
arrays
code | tests )
join (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
code | tests )
map (map through array, call function on each item
Params
-
array
(array|string) of items to iterate through -
fn
(function) to run on each item
Returns (array)
Example
code | tests )
range (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
components
code | tests )
addAnnotatedTextAria (Add aria to phrases in paragraphs, corresponds to annotation ids.
Params
-
content
(array) list of components
Returns (array) content
Example
code | tests )
addInSplashAds (Add in article ads to list of components in an article
Params
-
content
(array) the list of components in the article -
articleData
(object) the entire article's data, used to pull in the different ad units defined -
afterComponent
(string) the component type to insert the ad after
Returns (object) splash
Example
code | tests )
addOrderedIds (Add ordered ids to components within a componentlist
Params
-
content
(Array) list of components -
prefix
(string) prefix for the ids -
[offset]
(number) index to start at, defaults to 1
Returns (Array) content
Example
code | tests )
adsToDummies (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
code | tests )
displaySelf (Return the first component (from a list of components) with a truthy displaySelf
property. Used by Spaces.
Params
-
components
(array) withdisplaySelf
properties
Returns (object) first component with displaySelf: true
Example
code | tests )
displaySelfAll (Return all components (from a list of components) with a truthy displaySelf
property. Used by Spaces.
Params
-
components
(array) withdisplaySelf
properties
Returns (array) all components with displaySelf: true
Example
code | tests )
filterComponents (filters component references in a component list
Params
-
content
(array) list of components -
shouldKeep
(boolean) if true, only matching component references are returned; if false, then only non-matching component references are returned -
componentName
(string) name of the component to remove from the list (accepts multiple arguments)
Returns (array) content
Example
code | tests )
getComponentName (get a component's name from the reference
Params
-
ref
(string) full component uri
Returns (string)
Example
conditionals
code | tests )
compare (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 value -
operator
(string) to compare with -
right
(*) right value -
[options]
(object)
Returns (string) if inline, otherwise calls block functions
Example
code | tests )
if (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 truthiness -
value
(*) to print if conditional is truthy -
[options]
(object)
Returns (string) if inline, otherwise calls block functions
Example
code | tests )
ifAll (block helper for checking if ALL arguments passed in are truthy
Returns (string) calls block functions
Example
code | tests )
ifAny (block helper for checking if ANY arguments passed in are truthy
Returns (string) calls block functions
Example
code | tests )
ifNone (block helper for checking if NO arguments passed in are truthy
Returns (string) calls block functions
Example
code | tests )
modulo (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
code | tests )
unlessAll (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
html
code | tests )
perWordClasses (wraps each word in spans with classes allowing designers and devs to target individual words with css
Params
-
html
(string) to add classes to -
options
(object) -
[options.hash.perLetter]
(boolean) if you want an extra span wrapping each letter. defaults to true
Returns (string) words wrapped in classes
Example
code | no tests )
striptags (straight passthrough to striptags
Example
code | tests )
wordCount (counts the words in a string of text or html
Params
-
[html]
(string)
Returns (number) the number of words
Example
misc
code | tests )
default (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 check -
defaultValue
(*) value to return if first value is falsy
Example
code | tests )
extractImgHeight (Extract the height of a mediaplay image given the image URL.
Params
-
url
(string)
Returns (object) extracted height
Example
code | tests )
extractImgWidth (Extract the width of a mediaplay image given the image URL.
Params
-
url
(string)
Returns (Object) extracted width
Example
code | tests )
indexOf (get the index of something inside something else
Params
-
outside
(*) array, string, etc (anything withindexOf
) -
inside
(*) anything that can exist inside something else
Returns (number)
Example
code | tests )
set (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 context -
key
(string)_set()
key/path -
val
(*) value to set
Example
code | tests )
slugToSiteName (return comma-separated site names from comma-separated slugs
Params
-
slugs
(string) comma-separated string of slugs
Returns (string)
Example
numbers
code | tests )
add (Return the product of a
plus b
Params
-
a
(number) -
b
(number)
Returns (number)
Example
code | tests )
addCommas (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
-
num
(number|string)
Returns (string)
Example
code | tests )
addOrdinalSuffix (add ordinal after a number
e.g. 1
→ 1st
, 2
→ 2nd
, 3
→ 3rd
Params
-
num
(number|string) number to add ordinal after
Returns (string)
Example
code | tests )
divide (Return the result of a
divided by b
Params
-
a
(number) -
b
(number)
Returns (number)
Example
code | tests )
multiply (Return the product of a
multiplied by b
Params
-
a
(number) -
b
(number)
Returns (number)
Example
code | tests )
num (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
code | tests )
random (Returns a number within a specified range.
Params
-
min
(Number) -
max
(Number)
Returns (Number)
code | tests )
round (Return the rounded value of x
, optionally always rounding up or down
Params
-
x
(number|string) -
[direction]
(string) always roundx
up or down, expects values 'up' or 'down', otherwise just round
Returns (number)
Example
code | tests )
subtract (Return the product of a
minus b
Params
-
a
(number) -
b
(number)
Returns (number)
Example
code | tests )
toK (format thousands using k
e.g. 1000
→ 1k
Params
-
x
(number|string) number to format
Returns (string)
Example
objects
code | tests )
commaSeparated (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
code | tests )
getProp (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
code | tests )
stringify (stringify JSON
note: doesn't blow up on circular references
Params
-
obj
(object)
Returns (string)
Example
strings
code | tests )
capitalize (capitalize the first character in a string
Params
-
str
(string)
Returns (string)
Example
code | tests )
capitalizeAll (capitalize every word in a string
Params
-
str
(string)
Returns (string)
Example
code | tests )
concat (concatenate any number of strings
Returns (string) concatenated string
Example
code | tests )
includes (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.
note: handlebars returns booleans as strings, so only return a value if the substring is found
otherwise, return undefined (rather than false)
Params
-
string
(string) -
substring
(string)
Example
code | no tests )
kebabCase (straight passthrough to _kebabCase
Example
code | tests )
longestWord (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
code | tests )
lowercase (lower cases a string
note: non-strings will return emptystring
Params
-
str
(string)
Returns (string) lower cased
Example
code | tests )
randomString (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
code | tests )
removeSpaces (remove spaces, used by in-page id
attributes so we can do in-page links
(per the HTML spec IDs cannot have spaces)
Params
-
str
(string)
Returns (string)
Example
code | tests )
replace (replace all occurrences of a
with b
note: this does simple string replacement, not regex
Params
-
str
(string) to replace inside -
a
(string) to replace -
b
(string) the replacement
Returns (string)
Example
code | tests )
trim (trim leading and trailing whitespace from a string
Params
-
str
(string)
Returns (string)
Example
code | tests )
truncate (If a string is over a given length, truncate and append an ellipsis character to the end.
Params
-
str
(string) to shorten -
len
(number) desired length -
options
(object) -
[options.hash.suffix]
(string) to append to truncated string, defaulting to an ellipsis
Returns (string)
Example
time
code | tests )
articleDate (generate article dates and times, based on a relative format
Params
-
datetime
(Date|string) fordate-fns
to parse
Returns (string)
Example
code | tests )
dateMinimal (generate display date (without time), based on a relative format
Params
-
datetime
(Date|string) fordate-fns
to parse
Returns (string)
Example
code | tests )
formatLocalDate (Formats a date with date-fns
Params
-
date
(*) -
[format]
(string)
Returns (string)
code | no tests )
moment (No description
urls
code | tests )
urlencode (encode urls (ported from the nunjucks urlencode
filter)
note: handlebars-helpers
contains an encodeURI
helper, but it doesn't handle arrays or objects.
Params
-
obj
(*) data to encode
Returns (string) urlencoded data
Example
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.