Search code examples
javascriptjquery-templates

Bind tmpl to a jquery collection


Can anyone explain this behavior, imagine you have a jQuery collection, like this:

var list = $("#mySelect").children().filter(":selected");

Then I want to create a text-join to get "pX, pY" by using the following template:

var concatenation = $.tmpl("p${$data.val()}, ", list);

Result is a text node with only the first value in list "pX,".

Of course there are other ways to solve this example, eg.

"p" + $("#mySelect").val().join(", p");

With some trimming. But my question is about the tmpl behaviour, I don't understand why it only takes the first value.


Solution

  • your options is a jQuery selector result collection, it looks like the template engine does not understand that this is a collection and databind one row to the entire collection, thats why $data.val() return the first value (Thats the deafault behavior of a jquery selector).

    If you instead do

    var concatenation = $.tmpl("p${$data.value}, ", options.get());
    

    .get() will return the underlying DOM elements as an array, the template engine as no problem databind against these. Dont forget that you need to change your template from $data.val() to $data.value since you are now working directly against the DOM element