The most popular intro says that I can easily clone html templates within my document.
<template id="mytemplate">
<img src="" alt="great image">
<div class="comment"></div>
</template>
The word "template" however implies that you won't copy-paste it as is, unmodified. Template means that you want to update some variables with specific values. It recommends the following approach for updating the node:
var t = document.querySelector('#mytemplate');
// Populate the src at runtime.
t.content.querySelector('img').src = 'logo.png';
var clone = document.importNode(t.content, true);
document.body.appendChild(clone);
Isn't it perfect? There is querySelector to get the element so that you can update its attributes. I just do not understand why does he updates the template before cloning it. But that is not my question. The real question is that, in mine case, the location of variable to update is unknown. It can be either attribute or innerText in whatever template structure is. This is the most general and frequent use of template, I believe. So, I can ensure that the variable id is unique within the template, like #reply here
<template id="comment-template">
<li class="comment">
<div class="comment-author"></div>
<div class="comment-body"></div>
<div class="comment-actions">
<a href="#reply" class="reply">Reply</a>
</div>
</li>
</template>
ought to update the #reply
, but author does not explain how to do that. I succeeded to use innerHTML on the original template, document.querySelector('#mytemplate').innerHTML.replace(id, value)
but this breaks the template for later use, as explained above. I failed to update the cloned text. This is probably because template.clone produces a document fragment, which has no innerHTML. But, before pushing that forth, I decided to investigate for alternatives since I know that innerHTML/outerHTML is not quite standard.
Alternative for innerHTML? inspects the alternatives to innerHTML but again, they assume too much about the template. Instead of just replacing some specific identifiers with user values, they completely recreate the template, which defeats the whole notion of template. Template looses any sense once you recreate its whole code in the variable valuation. So, how is <template>
is supposed to use?