Search code examples
jqueryjquery-templates

How to attach data to jquery tmpl


Does anyone know how to attach the data item used to render a jQuery template to the resultant dom object?

given this tmpl:

<script id="sectionTemplate" type="text/x-jquery-tmpl">
<div class="story-writer-section sticker ${CssClasses}">
    <div class="title">
    <div class="delete-button sticker-button"/>
        ${SectionName}
    </div>
    <div class="story-writer-story-container">
    </div>
</div>

and this :

    $("#sectionTemplate")
        .tmpl(sections)
        .appendTo(".story-writer-section-container");

I'd like to attach each section to the result via a .data('section', data) so that I can access all the data later on because not all the data is rendered, eg id's etc that I need to get hold of later when doing things like delete.

Perhaps something like this...

        $("#sectionTemplate")
        .tmpl(sections)
        .appendTo(".story-writer-section-container").each(function (????) { 
                               this.data('section', ?????); 
                          });

But I have no idea how to get hold of the current data item used to render this tmpl.

Perhpas there is a way to include this in the template itself?

Any help much appreciated.


Solution

  • Ok, I have it solved. It looks like the data is already added to the element generated by .tmpl() and can be accessed like this:

    $.tmplItem(this).data
    

    Very nice, as usual, jQuery doesn't disappoint.