Links

Advanced templating (Handlebars)

Using the Handlebar templating engine to create advanced templates

Personalizing templates with Handlebars

By default, Lob uses a basic templating engine based on Mustache. If you would like to render complex personalizations, use the alternate Handlebars templating engine route through Lob API. Handlebars syntax allows you to populate, evaluate, and iterate using templates and API requests. The biggest advantage of this approach is quickly creating dynamic personalization without making any changes to your codebase. We can use advanced templating to make dynamic tables.

Creating a template

  1. 1.
    Start with any Handlebars-friendly template. Dynamic variables should be wrapped in double curly braces {{like_this}} . To the right is an example of a simple handlebars template.
<html>
Name is: {{user.name}}
Location is: {{user.location}}
</html>
  1. 2.
    To push your template to a Lob environment, use the /v1/templates API. Creating Handlebars templates via the Dashboard UI is not supported at this time. To specify that our service should use the Handlebars templating engine, you will need pass handlebars in the template request engine field as shown on the right.
POST
[/v1/templates](<https://api.lob.com/v1/templates>)/
‚Äč
{
"description":"Test Template",
"html":"<html>Name is: {{user.name}} <br>
Location is: {{user.location}} </html>",
"engine":"handlebars"
}
‚Äč
Response
‚Äč
{
"id": "tmpl_81ff8f64ce61285",
....
}

Template compilation API

You can use this newly created endpoint to test that your Handlebars template compiles as expected. To do that, use the /v1/templates/ endpoint and add your merge variable(s) as a dynamic URL query parameter. You can use this to inspect how your template will display with the merge variables passed in. The response is the same format that Lob will use to render your mailpiece.
GET
/v1/templates/:id/compile
?merge_vars={"someVar":"someVal"}
‚Äč
Returns HTML

Create a mailpiece using Handlebars

Now that your template has been created in a Lob environment, the templating engine has been set to handlebars, and you've tested out your template using the Template Compilation API, you can send a mailpiece request to the /v1/checks/, /v1/postcards/, /v1/letters/ or /v1/self_mailers/ endpoint as you normally would. In the request message body, use the merge_variables field to pass in dynamic values.
‚Äč

Helpers

Built in helpers

The below helpers can be used for many dynamic use cases. Helpers like if blocks can include nested built-in and customer helper conditionals (like if, and, or, eq, etc).
if
unless
each
with
lookup

#if

You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.
‚Äč
<div class="entry">
{{#if author}}
<h1>{{firstName}} {{lastName}}</h1>
{{/if}}
</div>
When you pass the following input to the above template:
‚Äč
{
author: true,
firstName: "Yehuda",
lastName: "Katz",
}
This will produce the result as below:
‚Äč
<div class="entry">
<h1>Yehuda Katz</h1>
</div>
If the input is an empty JSONObject {}, then author will become undefined and if condition fails, resulting in the output as follow:
<div class="entry"></div>
When using a block expression, you can specify a template section to run if the expression returns a falsey value. The section, marked by else is called an "else section".
‚Äč
<div class="entry">
{{#if author}}
<h1>{{firstName}} {{lastName}}</h1>
{{else}}
<h1>Unknown Author</h1>
{{/if}}
</div>

#unless

You can use the unless helper as the inverse of the if helper. Its block will be rendered if the expression returns a falsy value.
‚Äč
<div class="entry">
{{#unless license}}
<h3 class="warning">WARNING: This entry does not have a license!</h3>
{{/unless}}
</div>
If looking up license under the current context returns a falsy value, Handlebars will render the warning. Otherwise, it will render nothing.

#each

You can iterate over a list using the built-in each helper. Inside the block, you can use this to reference the element being iterated over.
‚Äč
<ul class="people_list">
{{#each people}}
<li>{{this}}</li>
{{/each}}
</ul>
when used with this context:
‚Äč
{
people: [
"Yehuda Katz",
"Alan Johnson",
"Charles Jolley",
],
}
will result in:
‚Äč
<ul class="people_list">
<li>Yehuda Katz</li>
<li>Alan Johnson</li>
<li>Charles Jolley</li>
</ul>
You can use the this expression in any context to reference the current context.
You can optionally provide an else section which will display only when the list is empty.
‚Äč
{{#each paragraphs}}
<p>{{this}}</p>
{{else}}
<p class="empty">No content</p>
{{/each}}
When looping through items in each, you can optionally reference the current loop index via {{@index}}.
{{#each array}} {{@index}}: {{this}} {{/each}}
Additionally for object iteration, {{@key}} references the current key name:
{{#each object}} {{@key}}: {{this}} {{/each}}
The first and last steps of iteration are noted via the @first and @last variables when iterating over an array. When iterating over an object only the @first is available. Nested each blocks may access the iteration variables via depth based paths. To access the parent index, for example, {{@../index}} can be used.

#with

The with-helper allows you to change the evaluation context of template-part.
‚Äč
{{#with person}}
{{firstname}} {{lastname}}
{{/with}}
when used with this context:
‚Äč
{
person: {
firstname: "Yehuda",
lastname: "Katz",
},
}
will result in:
Yehuda Katz
with can also be used with block parameters to define known references in the current block. The example above can be converted to
‚Äč
{{#with city as | city |}}
{{#with city.location as | loc |}}
{{city.name}}: {{loc.north}} {{loc.east}}
{{/with}}
{{/with}}
Which allows for complex templates to potentially provide clearer code than ../ depthed references allow for.
You can optionally provide an {{else}} section which will display only when the passed value is empty.
‚Äč
{{#with city}}
{{city.name}} (not shown because there is no city)
{{else}}
No city found
{{/with}}

#lookup

The lookup helper allows for dynamic parameter resolution using Handlebars variables.
This is useful for resolving values for array indexes.
‚Äč
{{#each people}}
{{.}} lives in {{lookup ../cities @index}}
{{/each}}
It can also be used to lookup properties of object based on data from the input. The following is a more complex example that uses lookup in a sub-expression to change the evaluation contextto another object based on a property-value.
‚Äč
{{#each persons as | person |}}
{{name}} lives in {{#with (lookup ../cities [resident-in])~}}
{{name}} ({{country}})
{{/with}}

Custom helpers

Custom helpers are additional functions that can assist in the formatting of your document. The documentation here is directly pulled from the associated third-party github repo. The helpers below are supported.
For uniformity with Handlebars' terminology, we use the wordfalsey instead of the more commonly used falsy.
Array helpers

‚Äč{{after}}‚Äč

Returns all of the items in an array after the specified index. Opposite of before.
Params
  • array {Array}: Collection
  • n {Number}: Starting index (number of items to exclude)
  • returns {Array}: Array exluding n items.
Example
<!-- array: ['a', 'b', 'c'] -->
‚Äč
{{after array 1}}
‚Äč
<!-- results in: '["c"]' -->

‚Äč{{arrayify}}‚Äč

Cast the given value to an array.
Params
  • value {any}
  • returns {Array}
Example
{{arrayify "foo"}}
‚Äč
<!-- results in: [ "foo" ] -->

‚Äč{{before}}‚Äč

Return all of the items in the collection before the specified count. Opposite of after.
Params
  • array {Array}
  • n {Number}
  • returns {Array}: Array excluding items after the given number.
Example
<!-- array: ['a', 'b', 'c'] -->
‚Äč
{{before array 2}}
‚Äč
<!-- results in: '["a", "b"]' -->

‚Äč{{eachIndex}}‚Äč

Implementation of the default Handlebars loop helper {{#each}} adding index (0-based index) to the loop content
Params
  • array {Array}
  • options {Object}
  • returns {String}
Example
<!-- array: ['a', 'b', 'c'] -->
‚Äč
{{#eachIndex array}}  
{{item}} is {{index}}
{{/eachIndex}}
‚Äč
<!-- results in 'a is 0, b is 1, c is 2' -->

‚Äč{{filter}}‚Äč

Block helper that filters the given array and renders the block for values that evaluate to true, otherwise the inverse block is returned.
Params
  • array {Array}
  • value {any}
  • options {Object}
  • returns {String}
Example
<!-- array: ['a', 'b', 'c'] -->
‚Äč
{{#filter array "foo"}}AAA
{{else}}BBB
{{/filter}}
‚Äč
<!-- results in: 'BBB' -->

‚Äč{{first}}‚Äč

Returns the first item, or first n items of an array.
Params
  • array {Array}
  • n {Number}: Number of items to return, starting at 0.
  • returns {Array}
Example
{{first "['a', 'b', 'c', 'd', 'e']" 2}}
‚Äč
<!-- results in: '["a", "b"]' -->

‚Äč{{forEach}}‚Äč

Iterates over each item in an array and exposes the current item in the array as context to the inner block. In addition to the current array item, the helper exposes the following variables to the inner block:
  • index
  • total
  • isFirst
  • isLast Also, @index is exposed as a private variable, and additional private variables may be defined as hash arguments.
Params
  • array {Array}
  • returns {String}
Example
<!-- accounts = [
{'name': 'John', 'email': '[email protected]'},
{'name': 'Malcolm', 'email': '[email protected]'},
{'name': 'David', 'email': '[email protected]'}
] -->
‚Äč
{{#forEach accounts}}
<a href="mailto:{{ email }}" title="Send an email to {{ name }}">
{{ name }}
</a>{{#unless isLast}}, {{/unless}}
{{/forEach}}

‚Äč{{inArray}}‚Äč

Block helper that renders the block if an array has the given value. Optionally specify an inverse block to render when the array does not have the given value.
Params
  • array {Array}
  • value {any}
  • options {Object}
  • returns {String}
Example
<!-- array: ['a', 'b', 'c'] -->
‚Äč
{{#inArray array "d"}}  foo{{else}}  bar{{/inArray}}
‚Äč
<!-- results in: 'bar' -->

‚Äč{{isArray}}‚Äč

Returns true if value is an es5 array.
Params
  • value {any}: The value to test.
  • returns {Boolean}
Example
{{isArray "abc"}}
<!-- results in: false --> 
‚Äč
<!-- array: [1, 2, 3] -->
‚Äč
{{isArray array}}
‚Äč
<!-- results in: true -->

‚Äč{{itemAt}}‚Äč

Returns the item from array at index idx.
Params
  • array {Array}
  • idx {Number}
  • returns {any} value
Example
<!-- array: ['a', 'b', 'c'] -->
‚Äč
{{itemAt array 1}}
‚Äč
<!-- results in: 'b' -->

‚Äč{{join}}‚Äč

Join all elements of array into a string, optionally using a given separator.
Params
  • array {Array}
  • separator {String}: The separator to use. Defaults to ,.
  • returns {String}
Example
<!-- array: ['a', 'b', 'c'] -->
‚Äč
{{join array}}
‚Äč
<!-- results in: 'a, b, c' --> 
‚Äč
{{join array '-'}}
‚Äč
<!-- results in: 'a-b-c' -->

‚Äč{{equalsLength}}‚Äč

Returns true if the the length of the given value is equal to the given length. Can be used as a block or inline helper.
Params
  • value {Array|String}
  • length {Number}
  • options {Object}
  • returns {String}
<!-- var value = "example" -->
‚Äč
{{equalsLength value 7}}
‚Äč
<!-- results in: true -->
‚Äč
<!-- var value = "example" -->
‚Äč
{{equalsLength value 5}}
‚Äč
<!-- results in: false -->

‚Äč{{last}}‚Äč

Returns the last item, or last n items of an array or string. Opposite of first.
Params
  • value {Array|String}: Array or string.
  • n {Number}: Number of items to return from the end of the array.
  • returns {Array}
Example
<!-- var value = ['a', 'b', 'c', 'd', 'e'] --> 
‚Äč
{{last value}}
‚Äč
<!-- results in: ['e'] --> 
‚Äč
{{last value 2}}
‚Äč
<!-- results in: ['d', 'e'] --> 
‚Äč
{{last value 3}}
‚Äč
<!-- results in: ['c', 'd', 'e'] -->

‚Äč{{length}}‚Äč

Returns the length of the given string or array.
Params
  • value {Array|Object|String}
  • returns {Number}: The length of the value.
Example
{{length '["a", "b", "c"]'}}
‚Äč
<!-- results in: 3 --> 
‚Äč
<! myArray = ['a', 'b', 'c', 'd', 'e']; -->
‚Äč
{{length myArray}}
‚Äč
<!-- results in: 5 --> 
‚Äč
<!-- myObject = {'a': 'a', 'b': 'b'}; -->
‚Äč
{{length myObject}}
‚Äč
<!-- results in: 2 -->

‚Äč{{map}}‚Äč

Returns a new array, created by calling function on each element of the given array. For example,
Params
  • array {Array}
  • fn {Function}
  • returns {String}
Example
<!-- array: ['a', 'b', 'c'], and "double" is afictitious function that duplicates letters -->
‚Äč
{{map array double}}
‚Äč
<!-- results in: '["aa", "bb", "cc"]' -->

‚Äč{{pluck}}‚Äč

Map over the given object or array or objects and create an array of values from the given prop. Dot-notation may be used (as a string) to get nested properties.
Params
  • collection {Array|Object}
  • prop {Function}
  • returns {String}
Example
// {{pluck items "data.title"}}
‚Äč
<!-- results in: '["aa", "bb", "cc"]' -->

‚Äč{{reverse}}‚Äč

Reverse the elements in an array, or the characters in a string.
Params
  • value {Array|String}
  • returns {Array|String}: Returns the reversed string or array.
Example
<!-- value: 'abcd' -->
‚Äč
{{reverse value}}
‚Äč
<!-- results in: 'dcba' -->
‚Äč
<!-- value: ['a', 'b', 'c', 'd'] -->
‚Äč
{{reverse value}}
‚Äč
<!-- results in: ['d', 'c', 'b', 'a'] -->

‚Äč{{some}}‚Äč

Block helper that returns the block if the callback returns true for some value in the given array.
Params
  • array {Array}
  • iter {Function}: Iteratee
  • {Options}: Handlebars provided options object
  • returns {String}
Example
<!-- array: [1, 'b', 3] -->
‚Äč
{{#some array isString}}  
Render me if the array has a string.{{else}} Render me if it doesn't.
{{/some}}
‚Äč
<!-- results in: 'Render me if the array has a string.' -->

‚Äč{{sort}}‚Äč

Sort the given array. If an array of objects is passed, you may optionally pass a key to sort on as the second argument. You may alternatively pass a sorting function as the second argument.
Params
  • array {Array}: the array to sort.
  • key {String|Function}: The object key to sort by, or sorting function.
Example
<!-- array: ['b', 'a', 'c'] -->
‚Äč
{{sort array}}
‚Äč
<!-- results in: '["a", "b", "c"]' -->

‚Äč{{sortBy}}‚Äč

Sort an array. If an array of objects is passed, you may optionally pass a key to sort on as the second argument. You may alternatively pass a sorting function as the second argument.
Params
  • array {Array}: the array to sort.
  • props {String|Function}: One or more properties to sort by, or sorting functions to use.
Example
<!-- array: [{a: 'zzz'}, {a: 'aaa'}] -->
‚Äč
{{sortBy array "a"}}
‚Äč
<!-- results in: '[{"a":"aaa"}, {"a":"zzz"}]' -->

‚Äč{{withAfter}}‚Äč

Use the items in the array after the specified index as context inside a block. Opposite of withBefore.
Params
  • array {Array}
  • idx {Number}
  • options {Object}
  • returns {Array}
Example
<!-- array: ['a', 'b', 'c', 'd', 'e'] -->
‚Äč
{{#withAfter array 3}}  {{this}}{{/withAfter}}
‚Äč
<!-- results in: "de" -->

‚Äč{{withBefore}}‚Äč

Use the items in the array before the specified index as context inside a block. Opposite of withAfter.
Params
  • array {Array}
  • idx {Number}
  • options {Object}
  • returns {Array}
Example
<!-- array: ['a', 'b', 'c', 'd', 'e'] -->
‚Äč
{{#withBefore array 3}}  {{this}}{{/withBefore}}
‚Äč
<!-- results in: 'ab' -->

‚Äč{{withFirst}}‚Äč

Use the first item in a collection inside a handlebars block expression. Opposite of withLast.
Params
  • array {Array}
  • idx {Number}
  • options {Object}
  • returns {String}
Example
<!-- array: ['a', 'b', 'c'] -->
‚Äč
{{#withFirst array}}  {{this}}{{/withFirst}}
‚Äč
<!-- results in: 'a' -->

‚Äč{{withGroup}}‚Äč

Block helper that groups array elements by given group size.
Params
  • array {Array}: The array to iterate over
  • size {Number}: The desired length of each array "group"
  • options {Object}: Handlebars options
  • returns {String}
Example
<!-- array: ['a','b','c','d','e','f','g','h'] -->
‚Äč
{{#withGroup array 4}}  
{{#each this}} {{.}}  {{each}}  <br>{{/withGroup}}
‚Äč
<!-- results in: -->
<!-- 'a','b','c','d'<br> -->
<!-- 'e','f','g','h'<br> -->

‚Äč{{withLast}}‚Äč

Use the last item or n items in an array as context inside a block. Opposite of withFirst.
Params
  • array {Array}
  • idx {Number}: The starting index.
  • options {Object}
  • returns {String}
Example
<!-- array: ['a', 'b', 'c'] -->
{{#withLast array}}  {{this}}{{/withLast}}
<!-- results in: 'c' -->

‚Äč{{withSort}}‚Äč

Block helper that sorts a collection and exposes the sorted collection as context inside the block.
Params
  • array {Array}
  • prop {String}
  • options {Object}: Specify reverse="true" to reverse the array.
  • returns {String}
Example
<!-- array: ['b', 'a', 'c'] -->
‚Äč
{{#withSort array}}{{this}}{{/withSort}}
‚Äč
<!-- results in: 'abc' -->

‚Äč{{unique}}‚Äč

Block helper that return an array with all duplicate values removed. Best used along with a each helper.
Params
  • array {Array}
  • options {Object}
  • returns {Array}
Example
<!-- array: ['a', 'a', 'c', 'b', 'e', 'e'] -->
‚Äč
{{#each (unique array)}}{{.}}{{/each}}
‚Äč
<!-- results in: 'acbe' -->
Comparison helpers

‚Äč{{and}}‚Äč

Helper that renders the block if both of the given values are truthy. If an inverse block is specified it will be rendered when falsey. Works as a block helper, inline helper or subexpression.
Params
  • a {any}
  • b {any}
  • options {Object}: Handlebars provided options object
  • returns {String}
Example
<!-- {great: true, magnificent: true} -->
‚Äč
{{#and great magnificent}}A{{else}}B{{/and}}
‚Äč
<!-- results in: 'A' -->

‚Äč{{compare}}‚Äč

Render a block when a comparison of the first and third arguments returns true. The second argument is the arithemetic operator to use. You may also optionally specify an inverse block to render when falsey.
Params
  • a {}
  • operator {}: The operator to use. Operators must be enclosed in quotes: ">", "=", "<=", and so on.
  • b {}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or if specified the inverse block is rendered if falsey.

‚Äč{{contains}}‚Äč

Block helper that renders the 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.
Params
  • collection {Array|Object|String}: The collection to iterate over.
  • value {any}: The value to check for.
  • [startIndex=0] {Number}: Optionally define the starting index.
  • options {Object}: Handlebars provided options object.
Example
<!-- array = ['a', 'b', 'c'] -->
‚Äč
{{#contains array "d"}}  This will not be rendered.{{else}}  This will be rendered.{{/contains}}

‚Äč{{default}}‚Äč

Returns the first value that is not undefined, otherwise the "default" value is returned.
Params
  • value {any}
  • defaultValue {any}
  • returns {String}

‚Äč{{eq}}‚Äč

Block helper that renders a block if a is equal to b. If an inverse block is specified it will be rendered when falsey. You may optionally use the compare="" hash argument for the second value.
Params
  • a {String}
  • b {String}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.
Example
{
"state":"California"
}
‚Äč
<html>
‚Äč
{{#if (**eq** state "California")}}
<p>Welcome to Cali</p>
{{else}}
<p>You\\'re not in California</p>
{{/if}}
‚Äč
</html>;
<!-- Results in 'Welcome to Cali' ‚Üí

‚Äč{{gt}}‚Äč

Block helper that renders a block if a is greater than b.
If an inverse block is specified it will be rendered when falsey. You may optionally use the compare="" hash argument for the second value.
Params
  • a {String}
  • b {String}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

‚Äč{{gte}}‚Äč

Block helper that renders a block if a is greater than or equal to b.
If an inverse block is specified it will be rendered when falsey. You may optionally use the compare="" hash argument for the second value.
Params
  • a {String}
  • b {String}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.

‚Äč{{has}}‚Äč

Block helper that renders a block if value has pattern. If an inverse block is specified it will be rendered when falsey.
Params
  • val {any}: The value to check.
  • pattern {any}: The pattern to check for.
  • options {Object}: Handlebars provided options object
  • returns {String}

‚Äč{{isFalsey}}‚Äč

Returns true if the given value is falsey. Uses the falsey library for comparisons. Please see that library for more information or to report bugs with this helper.
Params
  • val {any}
  • options {Options}
  • returns {Boolean}

‚Äč{{isTruthy}}‚Äč

Returns true if the given value is truthy. Uses the falsey library for comparisons. Please see that library for more information or to report bugs with this helper.
Params
  • val {any}
  • options {Options}
  • returns {Boolean}

‚Äč{{ifEven}}‚Äč

Return true if the given value is an even number.
Params
  • number {Number}
  • options {Object}: Handlebars provided options object
  • returns {String}: Block, or inverse block if specified and falsey.
Example
{{#ifEven value}}  render A{{else}}  render B{{/ifEven}}

‚Äč{{ifNth}}‚Äč

Conditionally renders a block if the remainder is zero when a operand is divided by b. If an inverse block is specified it will be rendered when the remainder is not zero.
Params
  • {}: {Number}
  • {}: {Number}
  • options {Object}: Handlebars provided options object