tamakisquare
tamakisquare

Reputation: 17077

JavaScript Templating: How should the partial template code be organized?

I am new to the world of JavaScript Templating.

Here I have a page, in which I don't know how the template code should be organized.

This is the relevant HTML When the page is first loaded:

...
<table id="color-codes">
  <tr>
    <td>red</td>
    <td>#FF0000</td>
  </tr>
  <tr>
    <td>blue</td>
    <td>#0000FF</td>
  </tr>
  <tr>
    <td>black</td>
    <td>#000000</td>
  </tr>
</table>
...

The user can add colors to the table. Each time a color is added, the browser dispatchs an AJAX request to the server. The server then returns a JSON object that has both the color name and the color code.

Upon receiving the JSON object, the client-end renders the template (below) with the JSON object and then insert the resultant DOM object into the end of the table.

The table-row template:

<tr id='tp-color-entry'>
  <td class='color-name'></td>
  <td class='color-code'></td>
</tr>

Question: Where should I place this template code? In HTML file? Or JS file? If in HTML file, how to prevent it to interfere with the page presentation/layout? If in JS file, do I just save assign it to a variable?

Note that I use Pure for JS Templating and Django as my server-end. And I always try to keep HTML and JS code into separate files.

Upvotes: 1

Views: 615

Answers (1)

icktoofay
icktoofay

Reputation: 129059

You can put it in a script tag with an unrecognized type attribute:

<script type="text/x-pure-template" id="color-entry-template">
    <tr id='tp-color-entry'>
        <td class='color-name'></td>
        <td class='color-code'></td>
    </tr>
</script>

Then it's a simple matter to retrieve the template:

document.getElementById('color-entry-template').textContent

Upvotes: 1

Related Questions