Skip to content

Commit

Permalink
Merge pull request #651 from smapiot/fix/piral-translate-do-not-repla…
Browse files Browse the repository at this point in the history
…ce-falsy-vars-with-empty-string

`piral-translate`: Do not replace falsy variables with an empty string
  • Loading branch information
FlorianRappl authored Dec 8, 2023
2 parents 7d4435e + 00539e7 commit e6c8a51
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/plugins/piral-translate/src/localize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const messages = {
en: {
hi: 'hello',
greeting: 'Hi {{name}}, welcome back',
secretNumber: 'The secret number is {{number}}.',
header: {
title: 'Hello world'
}
Expand Down Expand Up @@ -80,6 +81,12 @@ describe('Localize Module', () => {
expect(result).toBe('Hi , welcome back');
});

it('localizeGlobal does not replace falsy variables with an empty string', () => {
const localizer = new Localizer(messages, 'en');
const result = localizer.localizeGlobal('secretNumber', { number: 0 });
expect(result).toBe('The secret number is 0.');
});

it('localizeGlobal translates from global translations using passed nested translations', () => {
const localizer = new Localizer(messages, 'en');
const result = localizer.localizeGlobal('header.title');
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/piral-translate/src/localize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function defaultFallback(key: string, language: string): string {

function formatMessage<T extends object>(message: string, variables: T): string {
return message.replace(/{{\s*([A-Za-z0-9_.]+)\s*}}/g, (_match: string, p1: string) => {
return p1 in variables ? variables[p1] || '' : `{{${p1}}}`;
return p1 in variables ? variables[p1] ?? '' : `{{${p1}}}`;
});
}

Expand Down

0 comments on commit e6c8a51

Please sign in to comment.