Skip to content

Commit e5fc370

Browse files
fix(helpers): keep falsy but defined values in fillTemplate
fillTemplate replaced each ${var} with `templateVars[match] || ''`, which also dropped values that are defined but falsy, such as the number 0 or the boolean false. For example fillTemplate('${n}', {n: 0}) returned an empty string instead of '0'. This is noticeable in Pagination, where PaginationOptionsMenu passes numeric firstIndex, lastIndex and itemCount into a string toggle template. With an empty data set (itemCount of 0) the '0' was silently dropped from the toggle text. Use the nullish coalescing operator so only null or undefined values (for example a missing key) fall back to an empty string, while 0 and false are kept. Co-authored-by: eeshsaxena <eeshsaxena@gmail.com>
1 parent 4e13e7c commit e5fc370

2 files changed

Lines changed: 11 additions & 1 deletion

File tree

packages/react-core/src/helpers/__tests__/util.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,16 @@ test('fillTemplate interpolates strings correctly', () => {
9999
expect(actual).toEqual(expected);
100100
});
101101

102+
test('fillTemplate keeps falsy but defined values such as 0 and false', () => {
103+
expect(fillTemplate('count: ${n}', { n: 0 })).toEqual('count: 0');
104+
expect(fillTemplate('value: ${v}', { v: false })).toEqual('value: false');
105+
expect(fillTemplate('empty:${e}!', { e: '' })).toEqual('empty:!');
106+
});
107+
108+
test('fillTemplate replaces missing keys with an empty string', () => {
109+
expect(fillTemplate('x=${missing}', {})).toEqual('x=');
110+
});
111+
102112
test('text pluralize', () => {
103113
expect(pluralize(1, 'dog')).toEqual('1 dog');
104114
expect(pluralize(2, 'dog')).toEqual('2 dogs');

packages/react-core/src/helpers/util.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ export function sideElementIsOutOfView(container: HTMLElement, element: HTMLElem
114114
* @returns {string} The template string literal result
115115
*/
116116
export function fillTemplate(templateString: string, templateVars: any) {
117-
return templateString.replace(/\${(.*?)}/g, (_, match) => templateVars[match] || '');
117+
return templateString.replace(/\${(.*?)}/g, (_, match) => templateVars[match] ?? '');
118118
}
119119

120120
/**

0 commit comments

Comments
 (0)