Skip to main content Skip to footer

Wijmo Supports Template Literals

Template literals are a great JavaScript feature introduced in ES2015/ES6. They allow you to build multiline strings with interpolated values and make it easy to handle single and double quotes embedded in your strings.

We recently published a blog explaining how to write a tag function that adds formatting and globalization to template literals using Wijmo's Globalize class:

Template Literals Formatting and Globalization

We received great feedback on this and decided to move template literal support into the Wijmo core module. In the latest version of Wijmo (2019/V2), we added a "glbz" tag function so you can use Globalize with Template Strings without any extra code.

For example:

import { glbz } from "@grapecity/wijmo";

let price = 19.99;
let tax = 0.1125;
let total = glbz`The total price is <b>${price * (1 + tax)}:c2</b> (including ${tax}:p2 tax).`;
let today = glbz`Today is <b>${new Date()}:'dddd, MMMM d, yyyy'</b>.`;

document.getElementById('total-price').innerHTML = total;
document.getElementById('today').innerHTML = today;

The template literals above include format strings after each field. The format strings start with a colon sign (":"). Format strings that contain spaces must be enclosed in quotes.

The result is:

The total price is $22.24 (including 11.25 % tax).
Today is Monday, July 8, 2019.

Notice how the "glbz" tag function applies the currency and percentage formats to the values. The formats are included after each template element, prefixed by a colon sign (":").

The values are formatted using Wijmo's current culture, so numeric and date separators, currency signs, day, and month names are all automatically handled by Globalize.

For example, if you changed the current culture to Italian or German, the result would be:

    import '@grapecity/wijmo.cultures/wijmo.culture.it';
    ...

The total price is 22,24 € (including 11,25% tax).
Today is lunedì, luglio 8, 2019.

    import '@grapecity/wijmo.cultures/wijmo.culture.de';
    ...

The total price is 22,24 € (including 11,25 % tax).
Today is Montag, Juli 8, 2019. 

Notice the changes to decimal separator, currency sign, weekday, and month names.

The glbz function adds a lot of power to template literals. We hope you find it useful.

Happy coding!

Bernardo de Castilho

comments powered by Disqus