DEV Community

Discussion on: Template Literal expressions within the Template tag seem like a missed opportunity

Collapse
 
vonheikemen profile image
Heiker

If I understood correctly this article, I think lit-html is (close) to what you're looking for.

Collapse
 
davecranwell profile image
Dave Cranwell • Edited

Thanks, I'll give it a look. I've seen lit-html mentioned repeatedly in connection with htm in fact it was htm's latest release that got me thinking about all this. But from what I can understand htm is only usable in a preact/react environment.

At first glance I can't seem to see how to load a lit template from the DOM. My goal here is to write a JS component which contains no markup, but takes the markup it needs from the DOM. lit apparently does use <template> tags, but only as a background technique, not a primary source for rendering.

Collapse
 
vonheikemen profile image
Heiker • Edited

My goal here is to write a JS component which contains no markup, but takes the markup it needs from the DOM.

Oh I get it now. Nothing "lightweight" comes to mind.

I guess the closest thing that you could do with lit-html is evaluate the template somehow.

Don't do this at home.

<div id="app"></div>

<template id="test-template">
    hello ${data.name}
</template>

<script>
  import {html, render} from 'https://unpkg.com/lit-html?module';

  var generator = function(string) {
    var fn = new Function(
      'html',
      'data',
      `return html\`${string}\`;`
    );

    return fn.bind(null, html);
  };

  var template = document.getElementById('test-template');
  var helloComponent = generator(template.content.textContent);

  render(
    helloComponent({name: 'world'}),
    document.getElementById('app')
  );
</script>