Skip to content

Instantly share code, notes, and snippets.

@bendera
Created May 6, 2021 22:33
Show Gist options
  • Save bendera/8e97ab2cca4a7e6872238d7a7d3f54a2 to your computer and use it in GitHub Desktop.
Save bendera/8e97ab2cca4a7e6872238d7a7d3f54a2 to your computer and use it in GitHub Desktop.
lit-html newline to <br> directive
import {directive, NodePart, html} from 'lit-html';
export const nl2br = directive((val: string) => (part: NodePart) => {
if (!(part instanceof NodePart)) {
throw new Error('nl2br can only be used in content bindings');
}
const lines = val.split('\n');
const l = lines.length;
part.setValue(lines.map((line: string, i) => i === l - 1 ? line : html`${line}<br>`));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment