Can jquery template have a for loop
I need to create a jQuery template with a monthly dropdown and a schedule day dropdown in it. It seems like overkill I have to include a list of months and a daily list in each of my JSON model elements, which have values ββfrom 1 to 31 so that I can create variations with the {{each}} syntax.
I saw how you can add a dynamic array inside {{each}} in another answer: Can I declare local / temporary variables in a jQuery template?
I can probably just define an array inside it with values ββfrom 1 to 31. But even that's a little verbose. Is there a better way to do a for loop in jquery templates?
Perhaps I can find some date object to iterate over for a specific case, but what about a date not related to using a loop?
I want the loop to be fully defined in the template without using an external global variable. With a global variable, I could easily use {{each}}.
source to share
I found how to add another tag to jquery templates. Here is the definition for the tag. Add this after your script links 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 the sample for the textarea tag from Roel Kramers: http://blog.sterkwebwerk.nl/2010/12/15/custom-jquery-template-tags-1/
Also looking at the jquery.tmpl source to define each tag helped a lot.
The default is a for loop with 1 iteration. This is how you define the body of the template 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's a jsFiddle page to see it in action: http://jsfiddle.net/mjlang/qvzdV/
source to share