Search code examples
jqueryhtmltemplatesjquery-templates

jQuery Templates Plugin removes outer div tags before compiling


I am using the jQuery templates plugin to render separate html files as templates. One of my templates look like this:

<div class="row">
    <div class="span4">
        test1
    </div>
    <div class="span4">
        test2
    </div>
    <div class="span4">
       test3
    </div>
</div>

For testing purposes I am not actually rendering any data yet.

When I debug with firebug, I can see that my ajax call fetches the correct html (exactly as the above). I then use a json object (stored in a var called data) to populate my retrieved template (stored in a var called template) like so:

$.tmpl(template, data).appendTo('#person-item-placeholder');

The resulting html (as inspected by firebug) is this (notice the missing div element)

<div id="person-item-placeholder">
    <div class="span4">test1‌</div>
    <div class="span4">‌test2‌</div>
    <div class="span4">test3‌</div>
</div>

How do I prevent the template plugin from removing that element?


Solution

  • The jQuery.tmpl documentation is sort of vague in this area

    On the surface, what you have tried should work but one of the template parameter options reads :

    The template parameter can be .... An HTML element (or jQuery object that wraps an element) whose content is to be used as the template.

    The key word here is "content", in other words the wrapper is discarded though it doesn't say this occurs when a string is passed. Ignoring that, the symptom is exactly as described in the question.

    A possible solution would be to pre-wrap the template in a dummy container, eg a div.

    If I'm right, then this should work :

    $.tmpl('<div>+'template+'</div>', data).appendTo('#person-item-placeholder');
    

    Or maybe :

    $.tmpl($(template).wrap('<div/>'), data).appendTo('#person-item-placeholder');