clay / handlebars

A collection of helpers and partials for handlebars
MIT License
16 stars 8 forks source link

clayhandlebars

Build Status Coverage Status Code Climate

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

conditionals

html

misc

numbers

objects

strings

time

urls


arrays

join ( code | tests )

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

Params

Returns (string)

Example

{{ join ["a", "b", "c"] "-" }}
//=> "a-b-c"

map ( code | tests )

map through array, call function on each item

Params

Returns (array)

Example

{{ join (map [{ a: "1" }, { a: "2" }] (getProp "a")) }}
//=> "1, 2"

range ( code | tests )

return an array of numbers, in order
note: can be used inline or as a block helper (will iterate through all numbers)

Params

Returns (array)

Example

{{#range 1 5}}{{ this }}{{/range}}
//=> 1234

components

addAnnotatedTextAria ( code | tests )

Add aria to phrases in paragraphs, corresponds to annotation ids.

Params

Returns (array) content

Example

{{> component-list (addAnnotatedTextAria content)}}

addInSplashAds ( code | tests )

Add in article ads to list of components in an article

Params

Returns (object) splash

Example

{{> component-list (addInSplashAds content this "picks-links-container") }}

addOrderedIds ( code | tests )

Add ordered ids to components within a componentlist

Params

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

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

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

Returns (array) all components with displaySelf: true

Example

{{> component-list (displaySelfAll content) }}

filterComponents ( code | tests )

filters component references in a component list

Params

Returns (array) content

Example

{{> component-list (filterComponents content false "some-component" "another-component")}}

getComponentName ( code | tests )

get a component's name from the reference

Params

Returns (string)

Example

{{ getComponentName "domain.com/components/foo" }}
//=> foo

conditionals

compare ( code | tests )

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

Returns (string) if inline, otherwise calls block functions

Example

{{ compare 10 ">" 5 }}
//=> "true"

if ( code | tests )

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

Returns (string) if inline, otherwise calls block functions

Example

{{ if true "bar" else="baz" }}
//=> "bar"

ifAll ( code | tests )

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}}

ifAny ( code | tests )

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}}

ifNone ( code | tests )

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}}

modulo ( code | tests )

compare the modulo of two values to a third value

Params

Returns (string) if inline, otherwise calls block functions

Example

{{modulo 3 2 1}}
//=> true

unlessAll ( code | tests )

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

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!

wordCount ( code | tests )

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

default ( code | tests )

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

Example

{{ default "" "foo" }}
//=> foo

extractImgHeight ( code | tests )

Extract the height of a mediaplay image given the image URL.

Params

Returns (object) extracted height

Example

{{ extractImgHeight feedImgUrl }}
//=> 946

extractImgWidth ( code | tests )

Extract the width of a mediaplay image given the image URL.

Params

Returns (Object) extracted width

Example

{{ extractImgWidth feedImgUrl }}
//=> 1420

indexOf ( code | tests )

get the index of something inside something else

Params

Returns (number)

Example

{{ indexOf "foo" "o" }}
//=> 1

set ( code | tests )

set data into current context or other optional context/object
note: doesn't return anything

Params

Example

{{ set "a.b.c" "abc" }}{{ a.b.c }}
//=> "abc"

slugToSiteName ( code | tests )

return comma-separated site names from comma-separated slugs

Params

Returns (string)

Example

{{ slugToSiteName (commaSeparated crosspost) }}

numbers

add ( code | tests )

Return the product of a plus b

Params

Returns (number)

Example

{{ add 3 2 }}
//=> 5

addCommas ( code | tests )

add commas to numbers.
note: this overrides handlebars-helpers' addCommas helper because we want to preserve zeroes in decimals (for money)
e.g. 1234.501,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. 11st , 22nd , 33rd

Params

Returns (string)

Example

{{ addOrdinalSuffix 1 }}
//=> 1st

divide ( code | tests )

Return the result of a divided by b

Params

Returns (number)

Example

{{ divide 100 4 }}
//=> 25

multiply ( code | tests )

Return the product of a multiplied by b

Params

Returns (number)

Example

{{ multiply 10 10 }}
//=> 100

num ( code | tests )

converts things (usually strings) into numbers
note: this is useful if you need to parse user input

Params

Returns (string)

Example

{{ num "123" }}
//=> 123

random ( code | tests )

Returns a number within a specified range.

Params

Returns (Number)

round ( code | tests )

Return the rounded value of x , optionally always rounding up or down

Params

Returns (number)

Example

{{ round 1.5 "down" }}
//=> 1

subtract ( code | tests )

Return the product of a minus b

Params

Returns (number)

Example

{{ subtract 3 2 }}
//=> 1

toK ( code | tests )

format thousands using k
e.g. 10001k

Params

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

Returns (string)

Example

{{ commaSeparated {alpha: true, "bravo charlie": true} true }}
//=> "Alpha, Bravo charlie"

getProp ( code | tests )

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

Returns value of the property from the object

Example

{{ join (map [{ a: "1" }, { a: "2" }] (getProp "a"))}}
//=> "1, 2"

stringify ( code | tests )

stringify JSON
note: doesn't blow up on circular references

Params

Returns (string)

Example

{{{ stringify { a: "b" } }}}
//=> "{"a":"b"}"

strings

capitalize ( code | tests )

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"

concat ( code | tests )

concatenate any number of strings

Returns (string) concatenated string

Example

{{ concat "Foo" "Bar" "Baz" }}
//=> "FooBarBaz"

includes ( code | tests )

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

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

Returns (number) of letters in the longest word

Example

{{ longestWord "Foo Ba b" }}
//=> 3

lowercase ( code | tests )

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

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 ( code | tests )

replace all occurrences of a with b
note: this does simple string replacement, not regex

Params

Returns (string)

Example

{{ replace "Foo Bar" "Bar" "Baz" }}
//=> "Foo Baz"

trim ( code | tests )

trim leading and trailing whitespace from a string

Params

Returns (string)

Example

{{ trim "   Foo   " }}
//=> "Foo"

truncate ( code | tests )

If a string is over a given length, truncate and append an ellipsis character to the end.

Params

Returns (string)

Example

{{ truncate "Foo Bar" 4 }}
//=> "Foo…"

time

articleDate ( code | tests )

generate article dates and times, based on a relative format

Params

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

Returns (string)

Example

{{ dateMinimal "Fri, 13 Jan 2017 18:22:16 GMT" }}
//=> "Yesterday"

formatLocalDate ( code | tests )

Formats a date with date-fns

Params

Returns (string)

moment ( code | no tests )

No description

urls

urlencode ( code | tests )

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.