A collection of helpers and partials for handlebars
npm install --save clayhandlebars
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>
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');
Currently 56 helpers in 10 categories:
- addAnnotatedTextAria ( code | tests )
- addInSplashAds ( code | tests )
- addOrderedIds ( code | tests )
- adsToDummies ( code | tests )
- displaySelf ( code | tests )
- displaySelfAll ( code | tests )
- getComponentName ( code | tests )
- compare ( code | tests )
- if ( code | tests )
- ifAll ( code | tests )
- ifAny ( code | tests )
- ifNone ( code | tests )
- modulo ( code | tests )
- unlessAll ( code | tests )
- default ( code | tests )
- extractImgHeight ( code | tests )
- extractImgWidth ( code | tests )
- indexOf ( code | tests )
- set ( code | tests )
- slugToSiteName ( code | tests )
- 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 )
- 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 )
- articleDate ( code | tests )
- dateMinimal ( code | tests )
- formatLocalDate ( code | tests )
- moment ( code | no tests )
join all elements of array into a string, optionally using a given separator
array
(array)[sep]
(string) the separator to use (defaults to ', ')
Returns (string)
map through array, call function on each item
array
(array|string) of items to iterate throughfn
(function) to run on each item
Returns (array)
return an array of numbers, in order
note: can be used inline or as a block helper (will iterate through all numbers)
[start]
(number) on this number (defaults to 0)end
(number) on this number[options]
(object)
Returns (array)
Add aria to phrases in paragraphs, corresponds to annotation ids.
content
(array) list of components
Returns (array) content
Add in article ads to list of components in an article
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
Add ordered ids to components within a componentlist
content
(Array) list of componentsprefix
(string) prefix for the ids[offset]
(number) index to start at, defaults to 1
Returns (Array) content
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.
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
Return the first component (from a list of components) with a truthy displaySelf
property. Used by Spaces.
components
(array) withdisplaySelf
properties
Returns (object) first component with displaySelf: true
Return all components (from a list of components) with a truthy displaySelf
property. Used by Spaces.
components
(array) withdisplaySelf
properties
Returns (array) all components with displaySelf: true
get a component's name from the reference
ref
(string) full component uri
Returns (string)
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
left
(*) left valueoperator
(string) to compare withright
(*) right value[options]
(object)
Returns (string) if inline, otherwise calls block functions
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)
conditional
(*) to check for truthinessvalue
(*) to print if conditional is truthy[options]
(object)
Returns (string) if inline, otherwise calls block functions
block helper for checking if ALL arguments passed in are truthy
Returns (string) calls block functions
block helper for checking if ANY arguments passed in are truthy
Returns (string) calls block functions
block helper for checking if NO arguments passed in are truthy
Returns (string) calls block functions
compare the modulo of two values to a third value
dividend
(number)divisor
(number)remainder
(number)[options]
(object)
Returns (string) if inline, otherwise calls block functions
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
wraps each word in spans with classes allowing designers and devs to target individual words with css
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
striptags ( code | no tests )
straight passthrough to striptags
counts the words in a string of text or html
[html]
(string)
Returns (number) the number of words
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)
value
(*) to checkdefaultValue
(*) value to return if first value is falsy
Extract the height of a mediaplay image given the image URL.
url
(string)
Returns (object) extracted height
Extract the width of a mediaplay image given the image URL.
url
(string)
Returns (Object) extracted width
get the index of something inside something else
outside
(*) array, string, etc (anything withindexOf
)inside
(*) anything that can exist inside something else
Returns (number)
set data into current context or other optional context/object
note: doesn't return anything
[obj]
(object) context or object for storing data beyond current contextkey
(string)_set()
key/pathval
(*) value to set
return comma-separated site names from comma-separated slugs
slugs
(string) comma-separated string of slugs
Returns (string)
Return the product of a
plus b
a
(number)b
(number)
Returns (number)
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)
num
(number|string)
Returns (string)
add ordinal after a number
e.g. 1
→ 1st
, 2
→ 2nd
, 3
→ 3rd
num
(number|string) number to add ordinal after
Returns (string)
Return the result of a
divided by b
a
(number)b
(number)
Returns (number)
Return the product of a
multiplied by b
a
(number)b
(number)
Returns (number)
converts things (usually strings) into numbers
note: this is useful if you need to parse user input
x
(number|string) thing to convert into a number
Returns (string)
Returns a number within a specified range.
min
(Number)max
(Number)
Returns (Number)
Return the rounded value of x
, optionally always rounding up or down
x
(number|string)[direction]
(string) always roundx
up or down, expects values 'up' or 'down', otherwise just round
Returns (number)
Return the product of a
minus b
a
(number)b
(number)
Returns (number)
format thousands using k
e.g. 1000
→ 1k
x
(number|string) number to format
Returns (string)
Turn an object into a comma-delineated list of key names, depending if their values are true/false
obj
(object)shouldCapitalize
(boolean) capitalizes first word in each key
Returns (string)
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
prop
(string) key/path, passed to_get()
Returns value of the property from the object
stringify JSON
note: doesn't blow up on circular references
obj
(object)
Returns (string)
capitalize the first character in a string
str
(string)
Returns (string)
capitalize every word in a string
str
(string)
Returns (string)
concatenate any number of strings
Returns (string) concatenated string
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)
string
(string)substring
(string)
kebabCase ( code | no tests )
straight passthrough to _kebabCase
returns the number of characters in the longest word of a string. Punctuation is NOT ignored.
str
(string) string to search through
Returns (number) of letters in the longest word
lower cases a string
note: non-strings will return emptystring
str
(string)
Returns (string) lower cased
generate a random string
note: by default it generates an 8-character string
[prefix]
(string) string to append random stuff to[options]
(object)[options.hash.characters]
(number) generate string of a custom length
Returns (string)
remove spaces, used by in-page id
attributes so we can do in-page links
(per the HTML spec IDs cannot have spaces)
str
(string)
Returns (string)
replace all occurrences of a
with b
note: this does simple string replacement, not regex
str
(string) to replace insidea
(string) to replaceb
(string) the replacement
Returns (string)
trim leading and trailing whitespace from a string
str
(string)
Returns (string)
If a string is over a given length, truncate and append an ellipsis character to the end.
str
(string) to shortenlen
(number) desired lengthoptions
(object)[options.hash.suffix]
(string) to append to truncated string, defaulting to an ellipsis
Returns (string)
generate article dates and times, based on a relative format
datetime
(Date|string) fordate-fns
to parse
Returns (string)
generate display date (without time), based on a relative format
datetime
(Date|string) fordate-fns
to parse
Returns (string)
Formats a date with date-fns
date
(*)[format]
(string)
Returns (string)
moment ( code | no tests )
No description
encode urls (ported from the nunjucks urlencode
filter)
note: handlebars-helpers
contains an encodeURI
helper, but it doesn't handle arrays or objects.
obj
(*) data to encode
Returns (string) urlencoded data
Currently 1 partial:
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
This project is released under the MIT license.