Handlebars helpers used for various Cloud Four projects. Every helper is documented below, with a runnable example.
npm install --save-dev @cloudfour/hbs-helpersconst helpers = require('@cloudfour/hbs-helpers');
const Handlebars = require('handlebars');
for (const [name, helper] of Object.entries(helpers)) {
Handlebars.registerHelper(name, helper);
}const gulp = require('gulp');
const handlebars = require('gulp-compile-handlebars');
const helpers = require('@cloudfour/hbs-helpers');
gulp.task('default', () =>
gulp
.src('*.hbs')
.pipe(handlebars({ helpers }))
.pipe(gulp.dest('./dist'))
);Examples below use //=> to show what a helper renders.
The documentation below was generated once from the docblocks in lib/
(#207).
There is no build step that regenerates it, so when you change a helper's
docblock, update its section here to match.
all— Output a block (or its inverse) based on whether or not all of the supplied arguments are truthyand— Output a block (or its inverse) based on whether or not both of the supplied arguments are truthyany— Output a block (or its inverse) based on whether or not any of the supplied arguments are truthyaround— Slices a list based on a center-point and a maximum amount of "padding" before and afteraverage— Average an array of numeric valuescapitalize— Capitalize the first letter of a StringcapitalizeWords— Capitalize each word in a Stringcompare— Compare two values using logical operatorsconcat— Concatenate items into a single stringdefaultTo— Output the first provided value that exists, or fallback to a default if none dodummyImgSrc— Returns an escaped data URI for a placeholder image that can be used as the src attribute of an img elementiterate— Repeat a block a given amount of timesmath— Perform mathematical operations on one or two valuesmaybe— Output a block randomly (50% chance of being output)or— Output a block (or its inverse) based on whether or not either of the supplied arguments are truthyrandom— Generate a random integer or any other type of random content supported by Chance.jsrandomItem— Return only one random itemreplaceAll— Replace all occurrences of a string in another stringsplit— Splits a string or number by a separator string or numbersvg— Returns the contents of the SVG at the specified path, with any attributes passed along via the hash included on the root elementtimestamp— Format a date or time using Moment.jstoFixed— Format number to two fixed decimal points (like a price)toFraction— Format a decimal as a fractional HTML entity if possibletoJSON— Converts a string to JSON; useful when used in helper sub-expressionstoSlug— Format a string as a lowercase, URL-friendly valuetoTitle— Strip leading alphanumeric characters plus spaces from a string
Output a block (or its inverse) based on whether or not all of the supplied arguments are truthy.
- Parameters:
values...*— One or more values to test against. - Returns:
string | boolean - Since: v0.11.0
Deprecated. Use the more flexible
allhelper instead.
Output a block (or its inverse) based on whether or not both of the supplied arguments are truthy.
- Parameters:
leftany·rightany - Returns:
string - Throws:
Error— An error is thrown unless exactly two values are supplied. - Since: v0.0.1
Output a block (or its inverse) based on whether or not any of the supplied arguments are truthy.
- Parameters:
values...*— One or more values to test against. - Returns:
string | boolean - Since: v0.11.0
Slices a list based on a center-point and a maximum amount of "padding" before and after. Useful for pagination.
Supports an optional offset hash option in case your center
value isn't matching up with your array indexes.
- Parameters:
itemsArray— Collection to iterate over. ·centernumber— The center-point of the collection (for example, current page). ·paddingnumber— The amount of items to allow before or after the center. - Returns:
string - Since: v0.0.1
Average an array of numeric values.
- Parameters:
arrArray - Returns:
number— Returns the average of all values. - Since: v0.0.1
Capitalize the first letter of a String.
- Parameters:
strstring | *— String to capitalize. Other types will be converted. - Returns:
string - Throws:
TypeError— An error is thrown when no value is supplied. - Since: v0.4.0
Capitalize each word in a String. Works with punctuation and international characters.
- Parameters:
strstring | *— String to capitalize. Other types will be converted. - Returns:
string - Throws:
TypeError— An error is thrown when no value is supplied. - Since: v0.4.0
Compare two values using logical operators.
The operators are named after JavaScript's, but the equality ones do not
behave like JavaScript's, so read this before reaching for ==.
== and != are deep structural equality. No coercion happens, so
1 == "1" is false where JavaScript would say true; and objects are compared
by contents, so two separate arrays holding the same values are equal where
JavaScript would say false. This matters most for values arriving from JSON,
front matter, or query strings, where a number may well be a string.
=== and !== compare identity, matching JavaScript's === except that
NaN equals itself.
The relational operators (<, >, <=, >=) behave as expected, and
typeof compares against a type name such as "Array" or "Number".
- Parameters:
leftany·operatorstring·rightany - Returns:
(string | boolean)— formatted html if block, true/false if inline - Adapted from: github.com/assemble
Concatenate items into a single string.
- Parameters:
items...* - Returns:
string - Since: v0.8.0
Output the first provided value that exists, or fallback to a default if none do.
- Parameters:
value...* - Returns:
string - Since: v0.0.1
Returns an escaped data URI for a placeholder image that can be used as the src attribute of an img element.
- Parameters:
widthnumber·heightnumber - Returns:
string - Since: v0.3.0
Repeat a block a given amount of times.
- Since: v0.0.2
- Adapted from: https://github.com/fbrctr/fabricator-assemble
Perform mathematical operations on one or two values.
- Parameters:
leftany·operatorstring·rightany - Returns:
number
Output a block randomly (50% chance of being output). Useful for prototyping multiple content scenarios, outputting one or two "dummy" blocks of markup.
- Since: v0.0.1
Deprecated. Use the more flexible
anyhelper instead.
Output a block (or its inverse) based on whether or not either of the supplied arguments are truthy.
- Parameters:
leftany·rightany - Returns:
string - Throws:
Error— An error is thrown unless exactly two values are supplied. - Since: v0.0.1
Generate a random integer or any other type of random content supported by Chance.js.
- Parameters:
method=integerstring— Chance method to use. ·options.hashobject— Additional options to pass to method. - Returns:
any - Since: v0.4.0
random renders something different every time, so a static site that uses
it never builds the same way twice. random.create({ seed }) returns a copy
of the helper whose output repeats from one build to the next:
const random = require('@cloudfour/hbs-helpers/lib/random.js');
const randomItem = require('@cloudfour/hbs-helpers/lib/randomItem.js');
// One fixed seed for every render
Handlebars.registerHelper('random', random.create({ seed: 'my-site' }));
// Or a seed per page, e.g. in Eleventy
const perPage = { seed: (options) => options.data.root.page.inputPath };
Handlebars.registerHelper('random', random.create(perPage));
Handlebars.registerHelper('randomItem', randomItem.create(perPage));seedis any value Chance.js accepts as a seed, or a function that receives the helper's Handlebarsoptionsand returns one. Prefer a seed per page: with one fixed seed, every page draws from a single sequence, so adding a{{random}}to one template changes the output of every template rendered after it.- Each seed value gets one Chance instance, shared with
randomItemhelpers given the same seed. Calls within a page still differ from one another. - Seeded sequences keep advancing for as long as the process runs. If your
watch mode rebuilds without restarting, call
reset()on the helper before each build. It resets every seed, including thoserandomItemuses. - Since: v0.13.0
Return only one random item. If only one argument is provided and it is an array, it will return a random item from that array. Otherwise it will return one of the arguments.
- Parameters:
items...* - Returns:
any— One random item. - Since: v0.0.1
randomItem.create({ seed }) returns a copy of the helper whose output
repeats from one build to the next. It takes the same settings as
random.create(), and draws from the same sequence as
a random helper given the same seed.
Replace all occurrences of a string in another string. Can also be used on numbers, though they'll be treated as strings. Case sensitive.
- Parameters:
inputnumber | string·findnumber | string·replacenumber | string - Returns:
string - Since: v0.6.1
Splits a string or number by a separator string or number. Returns an array that can be iterated over.
- Parameters:
inputnumber | string·separatornumber | string - Returns:
Array - Since: v0.10.0
Returns the contents of the SVG at the specified path, with any attributes passed along via the hash included on the root element.
The file is inlined as-is and marked safe, so Handlebars will not escape it.
Any scripts, event handlers, or javascript: links it contains will run in
the rendered page. Only point this helper at SVGs you trust, such as your
project's own assets, never files that users upload.
Inspired by https://github.com/aredridel/npm-handlebars-helper-svg
- Parameters:
namestring— The path to the SVG. The extension may be omitted. - Returns:
string - Since: v0.6.0
By default, paths are resolved from the current working directory.
svg.create(settings) returns a copy of the helper with project-wide settings
applied, so templates don't have to repeat the path to your icons:
const svg = require('@cloudfour/hbs-helpers/lib/svg.js');
Handlebars.registerHelper('svg', svg.create({ basePath: './src/assets/images' }));basePath— The directory that paths are resolved from. Defaults toprocess.cwd().extName— The extension added when a path has none. Defaults to.svg.omitAttr— Attributes removed from the SVG's root element. Defaults to['xmlns', 'xmlns:xlink'], which aren't needed when the SVG is inline in HTML. Passing your own array replaces the default, so include those two if you still want them removed.- Since: v0.6.0
Format a date or time using Moment.js.
Defaults to UTC mode since most use-cases in markup-land do not take timezones into account, which results in some counter-intuitive output and inconsistent behavior.
- Parameters:
contextDate | string | number | Array | object - Returns:
string - Since: v0.0.1
Format number to two fixed decimal points (like a price).
- Parameters:
numnumber | string - Returns:
string - Since: v0.0.1
Format a decimal as a fractional HTML entity if possible.
- Parameters:
valuenumber - Returns:
string | number - Since: v0.0.1
Converts a string to JSON; useful when used in helper sub-expressions.
- Parameters:
strstring - Returns:
Array | object - Since: v0.0.1
Format a string as a lowercase, URL-friendly value.
- Parameters:
strstring - Returns:
string - Since: v0.0.1
Strip leading alphanumeric characters plus spaces from a string. Useful for converting filenames to more usable strings or IDs.
- Parameters:
namestring - Returns:
string - Since: v0.0.1