OL Connect 2022.2 Sneak peek: simplify templates with {{expressions}}

Avatar

When your OL Connect template requires many user scripts, it can quickly become hard to maintain. These scripts quite often perform basic find/replace tasks (aka Text Scripts). Having a script for each find/replace action feels like a lot of overhead for this seemingly easy task. Let’s see how the introduction of Handlebars expressions in OL Connect 2022.2 can make your template easier to maintain.

In version 2022.2, OL Connect Designer supports Handlebars expressions in the main editor. Expressions are variables wrapped with double curly braces, for example: {{firstName}}). They are automatically replaced with the value of the matching data field without requiring a User Script. This drastically reduces the number of scripts for a typical OL Connect template. These expressions are simple text strings, which makes them easy to insert, rearrange and style. Above all they are optimized for performance.

This image has an empty alt attribute

Note! The Handlebars feature changes the way data fields are added to the template (including Dynamic Tables). Therefore, this option is disabled for templates created in older versions. To enable the evaluation of expressions for a section choose: Section > Properties and select Evaluate Handlebars expressions. Note that you can use expressions side by side with User Scripts.

Adding expressions

To add an expression to the main editor, simply drag and drop one or more data fields from the Data Model pane into the section of your template.

This image has an empty alt attribute

Alternatively, double click a field in the Data Model panel to insert it at the cursor position or manually type the name of the field between double curly braces.

HTML String data fields

By using double curly braces, content is escaped. In the case of an HTML String data field this would show the literal HTML string. This is not likely the desired result. By using triple curly braces, the HTML content will be parsed into the section correctly. Adding an HTML String data field to the section using drag and drop automatically adds triple curly braces to the expression.

The following image shows a Data Model where the address of a recipient is stored in an HTML String field (note the <br> tag used for line breaks). The image on the right shows the result of the double and triple curly braces.

This image has an empty alt attribute

JSON data fields

In OL Connect 2022.2, JSON data fields show an expander arrow in the Data Model panel. Clicking this icon turns the JSON data field into a tree structure providing an easy way to inspect its child properties.

The following image shows an expanded JSON data field. Use drag and drop to add a property to the section in the main editor. This inserts an expression using the dot notation, which performs a look up of the value of that property on previewing and outputting the document.

Here, expressions for the address, postal code and city were added to the main editor. The {{address.street}} expression will look up the street property of the address data field.

This image has an empty alt attribute

Checking the Source view

The Source view shows that an expression is just plain text. There are no wrapping HTML elements (unless you apply formatting). OL Connect Designer applies syntax highlighting to distinguish expressions from normal text. This makes them easier to identify.

The following shows the source of a simple expressions-based address block. Line breaks (<br>) are added to put information on a new line (Tip! Press shift+enter in the Design mode to insert a line break).

<p>
    {{title}} {{firstName}} {{lastName}}<br>
    {{street}}<br>
    {{postal}} {{city}} 
</p>

The snippet below shows the same address block but this time using the traditional approach. In this scenario there was also a script for each field.

<p>
    <span class="title ol-scripted">@title@</span> <span class="firstName ol-scripted">@firstName@</span> <span class="lastName ol-scripted">@lastName@</span><br>
    <span class="street ol-scripted">@street@</span><br>
    <span class="postal ol-scripted">@postal@</span> <span class="city ol-scripted">@city@</span><br>
</p>

Formatting values

In some scenarios it is necessary to format values, for example uppercase all characters in a string or add a thousands separator to a number. For these purposes, the Handlebars implementation in OL Connect Designer comes with built-in data formatter helpers.

Helpers can be used to implement functionality that is not part of the Handlebars language itself. A Handlebars helper is in essence an expression followed by one or more parameters. For isntance, to convert a data field to upper case using OL Connects formatter helper : {{upperCase companyName}}.

In this case upperCase is the name of the OL Connect formatter helper to apply uppercase to all characters in a string and companyName is the parameter. The companyName parameter passes the value of the corresponding data field to the helper.

The image below shows a segment of an invoice with several formatter helpers applied.

This image has an empty alt attribute

OL Connect formatter helpers are based on the Formatter object found in the OL Connect Designer’s scripting API (examples are: upperCase, lowerCase, currency, currencyNoSymbol, grouped, dateShort, dateMedium, dateLong etc.).

Handlebars Text Helper

The Handlebars Text Helper wizard provides an easy way to concatenate multiple fields, format the values and add prefix/suffix content like spaces and line breaks (<br>). The user interface is identical to the Text Script wizard but in this case, it can be used with expressions.

To create a Handlebars Text Helper, select Handlebars Text Helper from the new Script menu in the Scripts panel. Enter a name for the expression, setup the fields and click OK to store the helper. The helper is added to the Control Script folder in the Scripts panel. Once created, add the expression to the section by typing the name of the helper between two curly braces or add it by using drag and drop.

The following shows the approach for creating a classic address block. Add a line for each data field using the plus icon on the right (or click the empty row below the last item). Add extra content in the Prefix and Suffix boxes. If a data field is empty, the respective line along with possible prefix and suffix content will be skipped. This prevents empty lines from showing up in the text. In the example below, this means there will be no empty line when the company field is blank.

This image has an empty alt attribute

Custom helpers

You can also write your own helpers. Custom helpers come in handy, and their result can be used via an expression. As such, they allow you to add functionality that is not part of the Handlebars implementation. Some good examples: showing today’s date or making a negative number turn red.

To create a custom helper, you’ll first need to create a Control Script in the Scripts panel and register the helper via Handlebars.registerHelper. The code snippet below shows a simple helper that uses JavaScript’s padStart method to pad a string with the number 0 until the string reaches 10 characters in length.

Handlebars.registerHelper('padStart', function(value){	
    return String(value).padStart(10, '0');
})

The helper is used like this: {{padStart invoiceNumber}}. In this case, padStart is the name of the helper and invoiceNumber is the parameter, which happens to be the name of a data field.

Below are some examples to get you inspired. There are many online resources and examples providing custom Handlebars helpers; when in need of a special helper or when looking for code snippets, Google is your friend (or you can always drop a question on the OL Connect forum).

Today

The following helper returns today’s date and applies the medium date notation.

/**
 * Inserts todays date in the dateMedium format'.
 * Usage: {{today}}
 * Result: Sep 14, 2022.
 */
Handlebars.registerHelper('today', function () {
    let today = new Date();
    return formatter.dateMedium( today )
})

In this case, today is the name of the helper. No parameters are needed as JavaScript’s Date() function is used to retrieve the current date. OL Connect’s formatter object is used to format the date. To add the expression to the section simply type its name between double curly braces in the main editor.

Make a negative number turn red

Custom helpers are also able to generate and return HTML. In this example the value provided in the parameter will be wrapped in a <span> element with an inline style applying the color red (alternatively use a CSS class instead of an inline style). An if statement is used to determine if the provided value contains a negative number using JavaScript’s Math.sign() function.

/**
 * Highlight negative values in red 
 * by wrapping the data with a span.
 * Usage: {{highlightNumber someDataField}}
 */ 
Handlebars.registerHelper('highlightNumber', function ( value ) {
    let result = value
    if( -1 === Math.sign(value) ) {
        result = '<span style="color:red">' + Handlebars.escapeExpression(value) + '</span>';
    }
    return Handlebars.SafeString( result )
})

Handlebars.SafeString prevents the result from being escaped when the template is rendered. This means double braces, instead of triple, can be used for the expression.

Expressions in dynamic tables

The introduction of expressions also allows them to be used in Dynamic Tables. When the evaluation of Handelbars expressions is enabled, dynamic tables inserted via the Insert Dynamic Table wizard will use expressions for data placeholders. In that scenario the table will not use the traditional data-field attributes stored in the source of the table (which still works).

This image has an empty alt attribute

Expressions in snippets

In version 2022.1 support for expressions were introduced for snippets. You can read all about it in the Get a grip on snippets with Handlebars article on our blog.

This image has an empty alt attribute

Backwards compatibility

As mentioned, the evaluation of Handlebars expressions is disabled for templates created in older versions. These templates will behave as before, on drag and drop of the data field the traditional placeholder is inserted, and a User Script is added to the Scripts panel.

To enable the evaluation of Handlebars, choose Section on the menu bar and select Properties. In the Properties dialog select the Evaluate Handlebars expressions option. Repeat this step for each section. Keep in mind that this changes the drag and drop behavior of data fields and will insert an expression instead of the traditional placeholder.

Tip! In case you want to convert your template to use expressions you can use the Find/Replace in the Source view to replace traditional placeholders (wrapped with the @-sign), with the curly braces notation. Select the Regular expressions option in the Find/Replace dialog. Set the Find field to: @([^@]+)@ and enter {{$1}} in the Replace with field.

This image has an empty alt attribute

Tagged in: 2022.2, Sneak peek



Leave a Reply

Your email address will not be published. Required fields are marked *