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 57 helpers in 10 categories:
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)
{{ join ["a", "b", "c"] "-" }}
//=> "a-b-c"
map through array, call function on each item
array
(array|string) of items to iterate throughfn
(function) to run on each itemReturns (array)
{{ 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)
[start]
(number) on this number (defaults to 0)end
(number) on this number[options]
(object) Returns (array)
{{#range 1 5}}{{ this }}{{/range}}
//=> 1234
Add aria to phrases in paragraphs, corresponds to annotation ids.
content
(array) list of componentsReturns (array) content
{{> component-list (addAnnotatedTextAria 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 afterReturns (object) splash
{{> component-list (addInSplashAds content this "picks-links-container") }}
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 1Returns (Array) content
{{> component-list (addOrderedIds content "annotation-") }}
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 instanceReturns (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) with displaySelf
propertiesReturns (object) first component with displaySelf: true
{{> component-list (displaySelf content) }}
Return all components (from a list of components) with a truthy displaySelf
property. Used by Spaces.
components
(array) with displaySelf
propertiesReturns (array) all components with displaySelf: true
{{> component-list (displaySelfAll content) }}
filters component references in a component list
content
(array) list of componentsshouldKeep
(boolean) if true, only matching component references are returned; if false, then only non-matching component references are returnedcomponentName
(string) name of the component to remove from the list (accepts multiple arguments)Returns (array) content
{{> component-list (filterComponents content false "some-component" "another-component")}}
get a component's name from the reference
ref
(string) full component uriReturns (string)
{{ getComponentName "domain.com/components/foo" }}
//=> foo
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
{{ 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)
conditional
(*) to check for truthinessvalue
(*) to print if conditional is truthy[options]
(object) Returns (string) if inline, otherwise calls block functions
{{ if true "bar" else="baz" }}
//=> "bar"
block helper for checking if ALL arguments passed in are truthy
Returns (string) calls block functions
{{#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
{{#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
{{#ifNone foo bar baz}}
all are falsy
{{else}}
not all are falsy
{{/ifNone}}
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
{{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
{{#unlessAll foo bar baz}}
not all are truthy
{{else}}
all are truthy
{{/ifAll}}
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 trueReturns (string) words wrapped in classes
{{{ perWordClasses "One two three" perLetter=false }}}
//=> <span class="_one">One</span> <span class="_two">two</span> <span class="_three">three</span>
straight passthrough to striptags
{{ striptags "<p><b>Hello</b> <em>World!</em></p>" }}
//=> Hello World!
counts the words in a string of text or html
[html]
(string) Returns (number) the number of words
{{wordCount "<div> This is <b> cool </b> </div>"}}
//=> 3
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{{ default "" "foo" }}
//=> foo
Extract the height of a mediaplay image given the image URL.
url
(string) Returns (object) extracted height
{{ extractImgHeight feedImgUrl }}
//=> 946
Extract the width of a mediaplay image given the image URL.
url
(string) Returns (Object) extracted width
{{ extractImgWidth feedImgUrl }}
//=> 1420
get the index of something inside something else
outside
(*) array, string, etc (anything with indexOf
)inside
(*) anything that can exist inside something elseReturns (number)
{{ indexOf "foo" "o" }}
//=> 1
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{{ set "a.b.c" "abc" }}{{ a.b.c }}
//=> "abc"
return comma-separated site names from comma-separated slugs
slugs
(string) comma-separated string of slugsReturns (string)
{{ slugToSiteName (commaSeparated crosspost) }}
Return the product of a
plus b
a
(number) b
(number) Returns (number)
{{ 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)
num
(number|string) Returns (string)
{{ addCommas "1234.50" }}
//=> "1,234.50"
add ordinal after a number
e.g. 1
→ 1st
, 2
→ 2nd
, 3
→ 3rd
num
(number|string) number to add ordinal afterReturns (string)
{{ addOrdinalSuffix 1 }}
//=> 1st
Return the result of a
divided by b
a
(number) b
(number) Returns (number)
{{ divide 100 4 }}
//=> 25
Return the product of a
multiplied by b
a
(number) b
(number) Returns (number)
{{ multiply 10 10 }}
//=> 100
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 numberReturns (string)
{{ num "123" }}
//=> 123
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 round x
up or down, expects values 'up' or 'down', otherwise just roundReturns (number)
{{ round 1.5 "down" }}
//=> 1
Return the product of a
minus b
a
(number) b
(number) Returns (number)
{{ subtract 3 2 }}
//=> 1
format thousands using k
e.g. 1000
→ 1k
x
(number|string) number to formatReturns (string)
{{ toK 1234.5 }}
//=> "1.2k"
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 keyReturns (string)
{{ 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
prop
(string) key/path, passed to _get()
Returns value of the property from the object
{{ join (map [{ a: "1" }, { a: "2" }] (getProp "a"))}}
//=> "1, 2"
stringify JSON
note: doesn't blow up on circular references
obj
(object) Returns (string)
{{{ stringify { a: "b" } }}}
//=> "{"a":"b"}"
capitalize the first character in a string
str
(string) Returns (string)
{{ capitalize "foo bar" }}
//=> "Foo bar"
capitalize every word in a string
str
(string) Returns (string)
{{ capitalizeAll "foo bar" }}
//=> "Foo Bar"
concatenate any number of strings
Returns (string) concatenated string
{{ 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.
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) {{ includes "hello world" "world" }}
//=> true
straight passthrough to _kebabCase
{{ kebabCase "Foo Bar Baz" }}
//=> "foo-bar-baz"
returns the number of characters in the longest word of a string. Punctuation is NOT ignored.
str
(string) string to search throughReturns (number) of letters in the longest word
{{ longestWord "Foo Ba b" }}
//=> 3
lower cases a string
note: non-strings will return emptystring
str
(string) Returns (string) lower cased
{{ lowercase "Foo" }}
//=> "foo"
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 lengthReturns (string)
{{ randomString "greatest-hit-" characters=3 }}
//=> "greatest-hit-z56"
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)
{{ removeSpaces "Foo Bar" }}
//=> "FooBar"
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 replacementReturns (string)
{{ replace "Foo Bar" "Bar" "Baz" }}
//=> "Foo Baz"
trim leading and trailing whitespace from a string
str
(string) Returns (string)
{{ trim " Foo " }}
//=> "Foo"
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 ellipsisReturns (string)
{{ truncate "Foo Bar" 4 }}
//=> "Foo…"
generate article dates and times, based on a relative format
datetime
(Date|string) for date-fns
to parseReturns (string)
{{ articleDate "Fri, 13 Jan 2017 18:22:16 GMT" }}
//=> "Yesterday at 6:22 p.m."
generate display date (without time), based on a relative format
datetime
(Date|string) for date-fns
to parseReturns (string)
{{ dateMinimal "Fri, 13 Jan 2017 18:22:16 GMT" }}
//=> "Yesterday"
Formats a date with date-fns
date
(*) [format]
(string) Returns (string)
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 encodeReturns (string) urlencoded data
{{ urlencode "&" }}
//=> "%26"
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.