javascriptjqueryjson

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">
    <div class="image">
         <img src="" />
    </div>
    <p class="list-group-item-text"></p>
</a>

jQuery

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

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

Solution

  • 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);
    });