Patrick Reck Patrick Reck - 6 months ago 32
jQuery Question

Defining a HTML "template" to append using JQuery

I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the

HTML
code below to a container element with some values.

Where can I put this HTML to re-use in a smart way?

<a href="#" class="list-group-item">
<table>
<tr>
<td><img src=""></td>
<td><p class="list-group-item-text"></p></td>
</tr>
</table>
</a>


JQuery

$('.search').keyup(function() {
$('.list-items').html(null);

$.each(items, function(index) {
// APPENDING CODE HERE
});

});

Answer

You could decide to make use of a templating engine in your project, such as:

If you don't want to include another library, John Resig offers a jQuery solution, similar to the one below.


Browsers and screen readers ignore unrecognized script types:

<script id="hidden-template" type="text/x-custom-template">
    <tr>
        <td>Foo</td>
        <td>Bar</td>
    <tr>
</script>

Using jQuery, adding rows based on the template would resemble:

var template = $('#hidden-template').html();

$('button.addRow').click(function() {
    $('#targetTable').append(template);
});