Skip to content

Commit 41ff0d6

Browse files
committed
Add "localizePrice" helper
1 parent 4ed3d29 commit 41ff0d6

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

helpers/localizePrice.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
'use strict';
2+
const utils = require('handlebars-utils');
3+
4+
const factory = () => {
5+
return function(price, locale='fr') {
6+
if (!utils.isObject(price) || !utils.isString(price.currency)
7+
|| isNaN(price.value) || !utils.isString(price.formatted)) {
8+
// Return empty string if this does not appear to be a price object
9+
return ''
10+
}
11+
12+
if (!utils.isString(locale) || locale.length < 2) {
13+
// Valid browser language strings are at least two characters
14+
// https://www.metamodpro.com/browser-language-codes
15+
// If provided locale is less than two characters (or not a string),
16+
// return the normal formatted price
17+
return price.formatted;
18+
}
19+
20+
// Detect ICU support
21+
const hasFullICU = (() => {
22+
try {
23+
const january = new Date(9e8);
24+
const spanish = new Intl.DateTimeFormat('es', { month: 'long' });
25+
return spanish.format(january) === 'enero';
26+
} catch (err) {
27+
return false;
28+
}
29+
})();
30+
31+
// If the if full ICU is not installed, fall back to normal price
32+
if (!hasFullICU){
33+
return price.formatted;
34+
}
35+
36+
// Try to format the price to the provided locale,
37+
// but if anything goes wrong,
38+
// just return the usual price
39+
// Could happen if the full ICU is not installed,
40+
// or if an invalid locale is provided.
41+
try {
42+
return new Intl.NumberFormat(
43+
locale, { style: 'currency', currency: price.currency}
44+
).format(price.value);
45+
}
46+
catch (err){
47+
return price.formatted;
48+
}
49+
};
50+
};
51+
52+
module.exports = [{
53+
name: 'localizePrice',
54+
factory: factory,
55+
}];

spec/helpers.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ describe('helper registration', () => {
4040
'lang',
4141
'langJson',
4242
'limit',
43+
'localizePrice',
4344
'money',
4445
'nl2br',
4546
'or',

0 commit comments

Comments
 (0)