Search code examples
javascriptjqueryclient-sidejquery-templates

How to write a loop withcondition in jquery template?


Consider following logic as requirement:

var count=4;

for(var i=0;i<count;i++)
{
  /* create a table row <tr></tr> */
}

Now if I where try do the same thing with my jquery template where in I want to try to do something as below:

<script id="MyTemplate" type="text/html">
        <table id="MyTable" class="Grid">            
            <tbody>
               {{each count}}
                <tr>
                  <td>${Name}</td>
                <tr>
           </tbody>
        </table>
</script>

where in the data I am trying to bind to template is :

var count=4;
var Name=["Peter","Michael","John","Thomas","James","Joseph","Mary","Simon"];

And the ouput I want my template to generate is:

<table id="MyTable" class="Grid">            
            <tbody>
                  <tr>
                    <td>Peter</td>
                    <td>Michael</td>
                    <td>John</td>
                    <td>Thomas</td>
                  <tr>
                  <tr>
                    <td>James</td>
                    <td>Joseph</td>
                    <td>Mary</td>
                    <td>Simon</td>
                  <tr>

           </tbody>
       </table>

I have already tried:

<script id="TestTemplate" type="text/x-jQuery-tmpl">
    Day:<br/>
    <table>
     <tbody>
        {{for(i=1;i<=${count};i++)}}
        <tr></tr>
        {{/for }}
     </tbody>
    </table>
</script>

But by doing the above implementation in the templates, the tmpl library throws "Template command not found" error.

Can anyone suggestion solution to do this?


Solution

  • You could try this:

    {{each(i) Name}}
        {{if i < count}}
            <tr></tr>
        {{/if}}
    {{/each}}