Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Don't error on 'null' in HTML templates #5602

Merged
merged 4 commits into from
Apr 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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