Handlebars Helpers Reference
This article is a reference for Stencil supported Handlebars helpers. It includes custom helpers documentation and a list of acceptlisted standard helpers.
Supported standard features
The following standard Handlebars features that are supported in Stencil themes. All documentation of standard Handlebars features can be found in the Handlebars documentation.
BigCommerce provided helpers
The following tables contains BigCommerce’s open source handlebars helpers which can be found at the BigCommerce GitHub repository.
Assets
Asset helpers are used to access and retrieve assets from your theme or store.
Templating
Helpers that are used to define and render templates.
Logic and control flow
Objects, arrays, and iteration
String manipulation
Utility and miscellaneous others
Custom data and variables
3rd party helpers and libraries
The following table contains generally accepted listed standard Handlebars helpers available to all Stencil themes. Each helper is linked to its GitHub documentation including parameters and examples.
Helpers documentation
Below is a list of example implementations and use cases for the custom helpers provided by BigCommerce platform. For more information, see the Handlebars GitHub Repo.
limit
Limits the number of items returned from an array; returns a new array.
Parameters
data(Array): Collection.limit(Number): Index specifying the number of items to exclude.
Example
Assume that {{cart.items}} returns 10 items. You can use this helper to limit that behavior to only the first four items.
pluck
Retrieves corresponding values from some or all elements in a collection using specified search key(s). Returns retrieved values in a comma-separated string. When used in conjunction with the built-in {{each}} helper, returns retrieved values in an array.
Parameters
limit,limit-value: Optional parameters to limit the number of results returned.collection(Object|Array): Collection.path(String): The string to search for.
Examples
If each category in categories contains an image object, use dot notation to access the image’s children:
cdn
A URL transformer for content delivery networks.
Parameters
assetPath(String): Path to the file containing static assets.
Example
To reference static assets staged locally outside your <theme-name> directory and uploaded using WebDAV, use the webdav: prefix before the assetPath. For example:
is transformed to:
Most non-image file types behave this way.
However, image files with the .jpg, .jpeg, .png, or .gif extensions are handled differently:
becomes
In both examples, the files were uploaded to the WebDAV /content/ directory, which acts as the root for cdn calls using the webdav: prefix.
To serve WebDAV assets outside the /content/ directory, avoid folder traversal or manual URL replacement with the cdn helper. Instead, use the getImageManagerImage helper, which serves content from the /dav/product_images/uploaded_images/ directory.
CDN custom endpoints
You can define custom CDN endpoints to use with the {{cdn}} helper. By doing so you can include large, high-resolution image assets in themes without exceeding BigCommerce’s 50 MB limit when bundling the theme for upload to BigCommerce.
You can also use a local version of the image in development and a remote version on a CDN such as Imgix in production. To do so, define custom CDN endpoints in your theme’s config.json file.
For example:
After defining the endpoint, you can use the short name in the same way as you use a webdav: protocol:
In local development, the helper returns the following:
In production environment, the helper returns the following:
As highlighted above, the helper is configured to rewrite local URLs to an assets/cdn/ subfolder. The stencil bundle command will exclude this local assets/cdn/ subfolder from the bundle that it creates. This filtering circumvents the 50 MB size limit on the resulting ZIP file.
Early Hint and cdn
Early Hints reduce page load time and perceived latency by allowing browsers to download critical assets earlier in the request lifecycle. For more information, see Early Hint.
Parameters
resourceHint- (String)- Corresponds to the
relattribute in<link>. - Value can be any of
preload,preconnect,prerender,dns-prefetch. - For more information, see rel on MDN Web Docs.
- Corresponds to the
as- (String)-
Corresponds to the
asattribute in<link>. -
Value can be any of
style,font,script,document. -
If an invalid value is provided,
aswon’t be included. -
This parameter is optional.
-
For more information, see as on MDN Web Docs.
-
crossorigin- (String)-
Value can be any of
no,anonymous,use-credentials. -
Defaults to
nowhen no value is provided. -
This parameter is optional.
-
For more information, see crossorigin on MDN Web Docs.
-
Example
The following script is an example of Early Hints usage in the Cornerstone theme:
You can view more Early Hints usage in Cornerstone’s templates/layout/base.html file by visiting the Cornerstone Repository.
EarlyHint
Retrieves the provided URL and produces an early hint to communicate important web page resources. The server indicates which site assets (such as CSS files, JS scripts, and fonts) a browser needs to render a page fully. When used in conjunction with the {{cdn}} helper, load times can improve by 30%.
Parameters
-
path(String): The URL that hosts the resource being hinted. -
rel(String): Valid arguments arepreload,preconnect,prerender, anddns-prefetch. -
as(String): Optional. Valid arguments arescript,style,font. -
crossorigin(String): Optional. Valid arguments areno(default),anonymous, anduse-credentials.
Examples
This example produces an early hint in a Link header that looks like:
The following example uses the getFontsCollection and stylesheet helpers. These helpers produce early hints by default, without using the earlyHint helper directly.
The output displays in a Link header that looks like:
moment
Use momentjs to format and calculate dates.
Examples
If you encounter an issue with the last day of the month, use one of the following fixes:
money
Formats number length, thousands delimiter, and decimal delimiter.
Parameters
value(Number): The number to format.n(Integer): Length of decimal.s(Mixed): Thousands delimiter.c(Mixed): Decimal delimiter.
Example
getFontLoaderConfig
Returns font-loader config as a JSON string.
Parameters
fontConfig(String): Font config in theGoogle_FontName_Weightformat.
Example
getFontsCollection
Returns <link> elements for configured fonts.
Example
encodeHtmlEntities
Returns a string with HTML entities encoded. You may optionally pass additional encoding arguments.
Parameters
string(String): String to encode with HTML entities.args(Boolean): Acceptlist of allowed named arguments. Allowed arguments:useNamedReferences,decimal,encodeEverything,allowUnsafeSymbols. Specifyarg='true'to use. For example,decimal='true'.
Examples
nl2br
Converts newline characters to <br /> tags.
Parameters
text(String): Text to convert.
Example
pre
Renders preformatted text. This helper will escape text.
Parameters
value(String): Text to format.
Example
resourceHints
Pre-fetches Google fonts. Outputs a formatted <link> tag for DNS-prefetch.
Example
stylesheet
Renders a link tag to insert a stylesheet into a theme; returns an HTML string. (This is required if you want Theme Editor to rewrite the stylesheet file when a merchant customizes their theme.)
Parameters
assetPath(String): Filepath to the theme’s CSS stylesheet file.options: You can append optional parameters as key/value pairs.
Example
lang
Maps keys to translation files based on the locale indicated by the visitor’s browser.
Parameters
translationKey(String)options: You can append optional parameters as key/value pairs.
Examples
langJson
Returns language translation keys as a JSON string.
Parameters
keyFilter(String): The language translation keys to render for the storefront locale/language.
Example
getContentImage
Returns a URL for an image uploaded to /dav/content/. To learn more about uploading files to your store’s server, see WebDAV.
Parameters
path(String): Image path relative to/dav/content/.width(Integer): Width in pixels.height(Integer): Height in pixels.
Example
getContentImageSrcset
Returns a srcset for an image uploaded to /dav/content/.
Parameters
path(String): Image path relative to/dav/content/.
Example
getImage
Returns <img> tag src value for images of a specified size. Values for the size parameter are defined in the settings array in config.json.
Parameters
stencilImage(String): A Stencil image.size(String): A key in thetheme_settingsobject.defaultImage(String): Optional default image URL to use if thestencilImageis undefined.
Example
getImageManagerImage
Returns an Image Manager image URL for an image uploaded to /dav/product_images/uploaded_images. To learn more about uploading files to your store’s server, see WebDAV.
Parameters
path(String): Image path relative to/dav/product_images/uploaded_images.width(Integer): Width in pixels.height(Integer): Height in pixels.
Example
getImageManagerImageSrcset
Returns an Image Manager image srcset for an image uploaded to /dav/product_images/uploaded_images. To return an image with a specified image width and height size, we recommend using the getImageManagerImage helper.
Parameters
path(String): Image path relative to/dav/product_images/uploaded_images.
Example
getImageSrcset
The getImageSrcset helper is a replacement for getImage which allows you to generate either a single image URL (for an <img> src) or a list of image sizes for srcset. Using the srcset attribute, you can specify a list of image sizes for the browser to choose from based on the expected size of the image on the page, the device’s pixel density, and other factors.
Parameters
stencilImage(String): A Stencil image.size(String): A key in thetheme_settingsobject.defaultImage(String): Optional default image URL to use if thestencilImageis undefined.
You can specify what sizes you want as named arguments on the helper.
Example
Default sizes
By specifying use_default_sizes=true on the helper, a srcset string will be constructed with a set of sizes chosen by BigCommerce to be optimal for most uses.
Default sizes:
Single 1x size
By specifying a single size as 1x, you can choose any image resolution. You can reference a value from the theme_settings object (similar to getImage), or you can specify your own size inline. getImageSrcset does not require theme_settings keys to be wrapped in quotes; they should be referenced directly.
Pixel density
By specifying several sizes using the pixel density descriptor, you can generate a srcset of different image resolutions for different pixel density screens as described in Resolution switching: Same size, different resolutions. For example, you can specify a 2x image for Retina screens, and a 1x image for normal screens.
As above, you can reference theme_settings keys or specify your own size inline.
Inherent width
By specifying several sizes using the inherent width descriptor, you can generate a srcset of different image resolutions based on width, which can in turn be selected by the browser based on the expected size of the image when the page is painted. It is recommended to use this together with a sizes attribute on the <img> element as described in Resolution switching: Different sizes. In Cornerstone, this is handled automatically via JavaScript.
As above, you can reference theme_settings keys or specify your own size inline.
any
Renders block if one or more parameters are true.
Parameters
arg(String|Number|Array|Object)
Example
A usage example is templates/components/category/shop-by-price.html, a category page in Stencil’s Cornerstone base theme that does not have faceted search turned on. Shoppers will see Shop by price filters instead of product filters.
In this component, the {{any}} helper is used to determine whether a shopper has selected one of the filters, and whether a “reset” button needs to be displayed:
all
Renders block if all parameters are true.
Parameters
arg(String|Number|Array|Object)
Example
compare
Compares values with JavaScript operators. Renders block if comparison of the first and third parameters returns true.
Parameters
-
a() -
operator(): The operator to use. Operators must be enclosed in quotes:>,=,<=, and so on.=====!=!==<><=>=typeof
-
b() -
options(Object): Options object. -
returns(String): Block, or if specified the inverse block is rendered if falsy.
contains
Renders block if collection has the given value, using strict equality (===) for comparison, otherwise the inverse block is rendered (if specified). If a startIndex is specified and is negative, it is used as the offset from the end of the collection.
Parameters
collection(Array|Object|String): The collection to iterate over.value(String|Number|Array|Object): The value to check for.
Example
for
Repeats block for a specified range from index a to index b. To protect against infinite loops, this helper is limited to 100 iterations.
Parameters
a(Number): Starting number.b(Number): Ending number. (Inclusive)
Example
if
Renders if block when if-statement evaluates to true; otherwise renders else block.
Parameters
arg(String|Number|Array|Object)
Example
or
Renders block if one or more parameters evaluates to true.
Parameters
arg(String|Number|Array|Object): Parameters can be of mixed types.
Example
unless
Renders a block if a statement is false; does not support operators for comparison expressions.
Parameters
arg(String|Number|Array|Object)
Example
option
Returns the given value of prop from this.options.
Example
{{option "a.b.c"}} returns “ddd”
get
Use property paths (a.b.c) to get a value or nested value from the context. Works as a regular helper or block helper. You can use return values from the concat helper as property paths.
Example
getObject
Use property paths (a.b.c) to get an object from the context. Differs from the get helper in that this helper will return the actual object including the given property key. This helper does not work as a block helper.
concat
Concatenates two strings.
Parameters
value(String)otherValue(String)
Example
multiConcat
Concatenates multiple strings.
Parameters
value(String)anotherValue(String)andAnotherValue(String)...(String/s)
Example
join
Joins an array of string elements into a single string.
Parameters
values(Array)separator(String)limit=<number>: An optional limit.
Example
json
Converts a JavaScript object into a JSON string.
Parameters
object(Object): A JavaScript object.
Example
occurrences
Returns the number of occurrences of substring within the given string.
Parameters
str(String)substring(String)
Example
replace
Replaces all instances of the first parameter in the second parameter with the child block.
Parameters
firstParam(?)secondParam(?)string(String)
Example
setURLQueryParam
Appends key values to a URL.
Parameters
url(String): The URL of the query parameter.key(String): The query parameter key.value(Number): The query parameter value of the stated key.
Example
stripQuerystring
Strips query string from a URL.
Parameters
url(String): The URL containing the query parameter.
Example
strReplace
Replaces some or all occurrences of a target substring within the subject string.
Parameters
subjectString(String): The original string to modify.targetSubstring(String): The substring insubjectStringto be replaced.newSubstring(String): The substring to insert in place oftargetSubstring.occurenceSelection(Integer): Optional. The number of occurrences oftargetSubstringto replace withnewSubstring. If you pass no argument or the supplied integer is greater than the number oftargetSubstringoccurrences,newSubstringwill replace all instances oftargetSubstring. A positive integernwill replaceninstances oftargetSubstring, starting from the left side of the string. Arguments of zero or less will replace no instances. Non-integer arguments may have unpredictable results.
Example
toLowerCase
Converts a string to lowercase.
Parameters
string(String): String you want to convert.
Example
truncate
Truncates a string.
Parameters
string(String): The string you want to truncate.length(Number): The desired length of the returned truncated string.
Example
block
Defines a block of content. You can overwrite it using the partial helper.
Parameters
string(String)
Example
dynamicComponent
Inserts a dynamic partial in the specified path.
Parameters
path(String): The path to insert a dynamic component in.
Example
inject
Injects key values into the jsContext helper.
Parameters
value(String): The value to inject.object(Object)
Example
jsContext
Returns a JSON representation of the data injected by the inject helper.
partial
Overrides content defined by the block helper.
Parameters
string(String)
Example
region
Specifies a widget region.
Parameters
name(String): The name of the region.
Example
assignVar
Assigns a variable for later use in the template and has a limit of 50 variables in storage.
Parameters
key(String)value(String|Number)
Example
getVar
Returns the variable set by assignVar.
Parameters
key(String)
Example
decrementVar
Decrements the variable set by assignVar by 1.
Parameters
key(String)
Example
incrementVar
Increments the variable set by assignVar by 1.
Parameters
key(String)
Example
JSONparse
Parse data with JSONparse.
Parameters
json(String)
Example
JSONparseSafe
Parse data safely with JSONparseSafe. This helper is similar to the JSONparse helper, but allows handling of incorrect JSON data. Returns parsed data when JSON is correct; otherwise, renders an else block.
Parameters
json(String): The data parsed by the helper.
Example
Contributing to helpers
BigCommerce’s custom Handlebars helpers are open source. To contribute, make a pull request to bigcommerce/paper-handlebars.