user3308774
user3308774

Reputation: 1374

Where do you store HTML that's going to be dynamically assembled via javascript?

I have a small javascript 'widget' of sorts that grows dynamically as users add items to it. The idea is that it has a top, middle, bottom, where the middle part is what grows.

+---------------+
|      TOP      |
+---------------+
|               |
|               |
|               |
+---------------+
|    BOTTOM     |
+---------------+

The top is a simple styled div with a handful of items in it:

 <div class="top">
        <a href="#" class="close-button">X</a>
        <h4>Title</h4>
    </div>

The body and bottom sections are more or less the same. My question is: Where should these be stored..? Right now, I'm keeping them in the body of the HTML document. Because I'm doing that, I either have to have CSS classes to set them to display: none, or I have to hide them on page load via javascript. Point being, it doesn't seem like the best solution.

I tried storing the divs as variables directly in my javascript, but with quote escaping, it quickly got really tricky... So I don't think that's the right way either.

What is the correct way to store HTML that you're going to use with javascript?

Upvotes: 1

Views: 57

Answers (1)

Arseny Smoogly
Arseny Smoogly

Reputation: 600

A nice trick by John Resig is <script type="text/html" id="myTemplate">...your template here...</script>.

Since browsers don't know how to handle scripts typed "text/html", they ignore that tag and it's contents.

You can later reference that tag by id or a class and extract it's contents for templating.

Original article: http://ejohn.org/blog/javascript-micro-templating/

Upvotes: 2

Related Questions