1

Let's say we have the following HTML template:

<template id="my_template">
  <div>
    <h4>Test Titel</h4>
    <div class="row">
      <label for="someinput">Stichwort:</label>
      <input id="someinput" type="text"/>
    </div>
  </div>
</template>

Now I like to render a list with multiple items based on that template. I know that we can just clone the template and use selectors on it as on a regular DOM.

But is there also an alternative way to clone, etc... but with data, so that we can set the content without using selectors, but variables?

Something like the following, we just declare the variable ID before adding the template?

<template id="my_template">
  <div>
    <h4>Test Titel</h4>
    <div class="row">
      <label for="someinput_${ID}">Stichwort:</label>
      <input id="someinput_${ID}" type="text"/>
    </div>
  </div>
</template>

I know it is possible with template literals, but I am just curious if this also works in any way with theses handy template tags?

Is it at all possible to set data in a temple tag without using selectors on it?

daslicht
  • 814
  • 10
  • 26
  • Not without using js. Most likely you can find a library for this – charlietfl Mar 17 '21 at 13:03
  • 1
    Minor nit: They're template *literals*, not template *strings*. The result of an untagged template literal is a string, but the result of a *tagged* template literal can be anything at all... :-) – T.J. Crowder Mar 17 '21 at 13:03
  • 1
    A complete aside: You can avoid using `for` and `id` by nesting the `input` inside the `label`, which associates them implicitly: ``. Not always ideal depending on how you're doing your styling, but possible. – T.J. Crowder Mar 17 '21 at 13:08
  • ```Minor nit: They're template literals, not template strings."``` fixed , thank you ! ```"Not without using js. Most likely you can find a library for this "``` I know i want it vanilla tho. And that it requires js is obvious but how – daslicht Mar 19 '21 at 18:41

1 Answers1

2

Is it at all possible to set data in a temple tag without using sectors on it ?

No, not in the way you mean. (The literal answer to the question quoted above is "yes" but only because you can modify the DOM without using selectors, per se — by doing the DOM traversal yourself. Not a useful "yes." )

HTML template tags don't have an "evaluate with these variables" method or similar. As you've said in the question, you could always write a function that uses a JavaScript template literal to build the HTML instead (and then use insertAdjacentHTML() or innerHTML to add it to the DOM).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • "JavaScript template literal to build the HTML instead (and then use insertAdjacentHTML()" That's, my current solution, I just wondered if that is also possible with template tags. – daslicht Mar 19 '21 at 18:36