Michael Lang
Michael Lang

Reputation: 1180

Can a jquery template have a for loop

I need to build a jQuery template that has a month dropdown and a day of the month dropdown in it. It seems like overkill for me to have to include a month list and a day list in each of my JSON model items that has values 1 to 31 just so that I can build options with the {{each}} syntax.

I've seen how you can add a dynamic array inside of {{each}} in another answer: Can I declare local/temp variables within a jQuery template?

I can probably just define an array inside that with values 1 to 31. But even that is a little verbose. Is there a better way to do a for loop in jquery templates?

I can probably find some date object to iterate for the date specific case, but what about a non date related for loop use case?

I want the loop fully defined in the template body without using an external global variable. With a global variable, I could easily use {{each}}.

Upvotes: 3

Views: 9487

Answers (1)

Michael Lang
Michael Lang

Reputation: 1180

I've found how to add another tag to jquery templates. Here is the for tag definition. Add this after your script references to jquery and jquery.tmpl.js:

(function ($) {
$.extend(jQuery.tmpl.tag, {
    "for": {
        _default: {$2: "var i=1;i<=1;i++"},
        open: 'for ($2){',
        close: '};'
    }
});
})(jQuery);

Thanks for a sample for a textarea tag by Roel Kramers: http://blog.sterkwebwerk.nl/2010/12/15/custom-jquery-template-tags-1/

Also viewing the jquery.tmpl source for the definition of the each tag helped a lot.

The default is a for loop with 1 iteration. Here is how you define a template body to use it:

<script id="TestTemplate" type="text/x-jQuery-tmpl">
    Day:<br/>
    <select name="DayOfMonth">
        {{for(i=1;i<=31;i++)}}
        <option value="${i}">${i}</option>
        {{/for }}
    </select>
</script>​

Here is a jsFiddle page to see it in action: http://jsfiddle.net/mjlang/qvzdV/

Upvotes: 13

Related Questions