Skip to content

Instantly share code, notes, and snippets.

@jimmont
Created February 24, 2025 15:58
Show Gist options
  • Save jimmont/d472b20f8dcb15bce88f9572751e7a46 to your computer and use it in GitHub Desktop.
Save jimmont/d472b20f8dcb15bce88f9572751e7a46 to your computer and use it in GitHub Desktop.
lit templates toString: a template and its content converted to a string (LitElement)
/* convert lit templates and all their stuff and things to strings:
const things = 'things';
lit_toString(html`<b>stuff and ${ [ things ] }</b>`)
// `<b>stuff and things</b>`
*/
export function lit_toString(data) {
// template
const {strings = null, values = []} = data ?? {};
// if not a template
if(!strings) return data ?? '';
return strings.reduce((res, txt, i)=>{
const v = values[i] ?? '';
res.push(txt);
if(Array.isArray(v)){
res.push(...(v.map(lit_toString)))
}else{
res.push( lit_toString(v) );
}
return res;
}, []).join('');
}
/*
// str info at https://lit.dev/docs/localization/overview/#strings-with-expressions
console.log(test_lit_toString({html}, html`<b>${ str`${ 123 }` }</b>`));
console.log(test_lit_toString({html}));
*/
export function test_lit_toString({html=()=>{}, src='./image.webp', make=lit_toString}, ...tests){
return [
html`<img src=${src} />`,
html`<b>${ [1,2,html`<b>bb${7}b</b>`] }</b>`,
...tests
].map( stuff=> make(stuff) )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment