Skip to content

Commit

Permalink
fix: Don't error on 'null' in HTML templates (#5602)
Browse files Browse the repository at this point in the history
* fix: Don't render 'null' in HTML templates

* Add test for null handling

* Add changeset for html package
  • Loading branch information
mwest1066 authored and nwalters512 committed Apr 11, 2022
1 parent 906ee0d commit b46757b
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/fresh-months-tap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@prairielearn/html': patch
---

Fix rendering of null values in templates
4 changes: 4 additions & 0 deletions packages/html/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ describe('html', () => {
it('omits boolean values from template', () => {
assert.equal(html`<p>${true}${false}</p>`.toString(), '<p></p>');
});

it('omits nullish values from template', () => {
assert.equal(html`<p>${null}${undefined}</p>`.toString(), '<p></p>');
});
});

describe('escapeHtml', () => {
Expand Down
7 changes: 5 additions & 2 deletions packages/html/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ function escapeValue(value: unknown): string {
return value.map((val) => escapeValue(val)).join('');
} else if (typeof value === 'string' || typeof value === 'number') {
return ejs.escapeXML(String(value));
} else if (value == null) {
// undefined or null -- render nothing
return '';
} else if (typeof value === 'object') {
throw new Error('Cannot interpolate object in template');
throw new Error(`Cannot interpolate object in template: ${JSON.stringify(value)}`);
} else {
// This is undefined, null, or a boolean - don't render anything here.
// This is boolean - don't render anything here.
return '';
}
}
Expand Down

0 comments on commit b46757b

Please sign in to comment.