Javascript best practices & conventions, such as those emphasized by John Resig and by Nicholas Zachas, author of book Maintainable JavaScript, suggest using HTML comments or script tags with a custom type to store HTML templates.
Comment example:
<div id="myTemplate">
<!-- <ul><li>$item</li></ul> -->
</div>
<script>
var myTemplate = document.getElementById('myTemplate').childNodes[0].data;
var myHtml = myTemplate.replace(/\$item/g, itemValue);
</script>
Script tag example:
<script id="myTemplate" type="text/x-html-template">
<ul><li>$item</li></ul>
</script>
<script>
var myTemplate = document.getElementById('myTemplate').innerHTML;
var myHtml = myTemplate.replace(/\$item/g, itemValue);
</script>
I strongly dislike the comment-based templating because comments are supposed to be just that--comments, intended to be ignored by the functioning application--and as such I'm a little bewildered as to how it even gets to be suggested by JS gurus.
The script tag templating makes a lot more sense, and I'd normally call it a best if not wonderful practice because the purpose and initial non-function are well-delineated. My only issue is that in some modern editors the color highlighting, autocompletion, auto markup validation, etc., are all lost while working within the script tag.
An approach to templating I've taken in the past is to put it all in a container div, then classify the container div as class="template", then in CSS mark it as ".template { display: none; }".
<div id="myTemplate" class="template">
<ul><li>$item</li></ul>
</div>
<script>
var myTemplate = document.getElementById('myTemplate').innerHTML;
var myHtml = myTemplate.replace(/\$item/g, itemValue);
</script>
This has worked fine for me, although the DOM parser and renderer obviously processes the data up front unnecessarily, but I'm not sure whether this is really all that big of an issue or not, as long as the templating constructs do not break HTML validity rules.
My question, then, is, what am I missing? Is the only reason why this third approach to storing template markup--that is, putting it in the DOM as display:none--is discouraged because the DOM parser and renderer will process it anyway? Or are there other reasons, perhaps technical, that I haven't come across yet? I'd like to know because, again, I want to take advantage of my editor's ability to help me fine tune a proper HTML template.