npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

clayhandlebars

v5.0.2

Published

A collection of helpers and partials for handlebars

Downloads

2,221

Readme

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

  • array (array)
  • [sep] (string) the separator to use (defaults to ', ')

Returns (string)

Example

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

map ( code | tests )

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

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

  • [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 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

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

addOrderedIds ( code | tests )

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

{{> component-list (addOrderedIds content "annotation-") }}

adsToDummies ( code | tests )

Given a list of component instance objects, replace each ad componentwith a site's "dummy" ad instance, matching the properties of the adinstance 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) }}

filterComponents ( code | tests )

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

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

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

  • left (*) left value
  • operator (string) to compare with
  • right (*) right value
  • [options] (object)

Returns (string) if inline, otherwise calls block functions

Example

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

if ( code | tests )

overwrite default handlebars 'if' helperthis 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

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

  • dividend (number)
  • divisor (number)
  • remainder (number)
  • [options] (object)

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

  • 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

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

  • [html] (string)

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

  • value (*) to check
  • defaultValue (*) value to return if first value is falsy

Example

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

extractImgHeight ( code | tests )

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

Params

  • url (string)

Returns (object) extracted height

Example

{{ extractImgHeight feedImgUrl }}
//=> 946

extractImgWidth ( code | tests )

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

Params

  • url (string)

Returns (Object) extracted width

Example

{{ extractImgWidth feedImgUrl }}
//=> 1420

indexOf ( code | tests )

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

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

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

add ( code | tests )

Return the product of a plus b

Params

  • a (number)
  • b (number)

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

  • num (number|string)

Returns (string)

Example

{{ addCommas "1234.50" }}
//=> "1,234.50"

addOrdinalSuffix ( code | tests )

add ordinal after a numbere.g. 11st , 22nd , 33rd

Params

  • num (number|string) number to add ordinal after

Returns (string)

Example

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

divide ( code | tests )

Return the result of a divided by b

Params

  • a (number)
  • b (number)

Returns (number)

Example

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

multiply ( code | tests )

Return the product of a multiplied by b

Params

  • a (number)
  • b (number)

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

  • x (number|string) thing to convert into a number

Returns (string)

Example

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

random ( code | tests )

Returns a number within a specified range.

Params

  • min (Number)
  • max (Number)

Returns (Number)

round ( code | tests )

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

subtract ( code | tests )

Return the product of a minus b

Params

  • a (number)
  • b (number)

Returns (number)

Example

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

toK ( code | tests )

format thousands using k e.g. 10001k

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"

getProp ( code | tests )

get property in objectthis 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 ( code | tests )

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

Params

  • obj (object)

Returns (string)

Example

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

strings

capitalize ( code | tests )

capitalize the first character in a string

Params

  • str (string)

Returns (string)

Example

{{ capitalize "foo bar" }}
//=> "Foo bar"

capitalizeAll ( code | tests )

capitalize every word in a string

Params

  • str (string)

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 theindexOf helper, except it uses String.prototype.includes() and returns aboolean.note: handlebars returns booleans as strings, so only return a value if the substring is foundotherwise, return undefined (rather than false)

Params

  • string (string)
  • substring (string)

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

lowercase ( code | tests )

lower cases a string note: non-strings will return emptystring

Params

  • str (string)

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

  • str (string)

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

  • str (string) to replace inside
  • a (string) to replace
  • b (string) the replacement

Returns (string)

Example

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

trim ( code | tests )

trim leading and trailing whitespace from a string

Params

  • str (string)

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

  • 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

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

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

  • obj (*) data to encode

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.