Underscore template conditional can be reduced I have 11 data items and would like to print them as a group. Each group will have header and at the end of the group I need to print continue label.

For that, I use this Underscore template and multiple conditions.  I'd like to make this more compact.

&lt;script type="text/template" id="header"&gt;
&lt;div id="recourseParameter"&gt;
    &lt;h1&gt; Parameter : &lt;%= parameterCode %&gt;  &lt;/h1&gt;
    &lt;table&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th colspan=5&gt;header&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
&lt;/script&gt;
&lt;script id="closer" type="text/template"&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;
&lt;/script&gt;
&lt;script id="footer" type="text/template"&gt;
    &lt;/tbody&gt;
    &lt;/table&gt;
        &lt;span&gt;All are done&lt;/span&gt;
&lt;/script&gt;

&lt;script type="text/template" id="recourseParameterTemp"&gt;

    &lt;% var limit = 3, dLength = recourseParameter.length %&gt;
    &lt;% var done = false %&gt;
    &lt;% _.each(recourseParameter, function (item, index) { %&gt;

            &lt;% if (index % limit == 0 )  { %&gt;
                &lt;%= _.template($('#header').html())({"parameterCode":parameterCode}) %&gt;
            &lt;% } %&gt;

            &lt;% if(item.description) { %&gt;
                &lt;tr&gt;
                    &lt;td colspan=5&gt;&lt;%= item.description %&gt;&lt;/td&gt;
                &lt;/tr&gt;
            &lt;% } %&gt;

            &lt;% if ((index+1) % limit == 0 )  { %&gt;
                    &lt;%= _.template($('#closer').html())() %&gt;
                        &lt;span&gt;Continue ... &lt;/span&gt; 
                    &lt;/div&gt;
            &lt;% }  %&gt;

    &lt;% }) %&gt;

    &lt;%= _.template($('#footer').html())() %&gt;

&lt;/script&gt;
If I understand your code correctly, it looks like you want to render tables with 3 records each, with the #header template for the top of each table and the #closer template for the bottom of each table, except for the last one, which should end with #footer instead of #closer.

First, the little things:


I think you have some unused variables in your code: It looks like dLength and done are never used.
limit is a magic number and seems out of place in your template. If I were you I would pass that number to the template function along with your other data.
You render &lt;div id="resourceParameter"&gt; several times, but element IDs must be unique in a document. We shouldn't re-use an ID.
For the last table, the &lt;/div&gt; is never rendered, so the above div is never closed! Fixing this is discussed below.
You're compiling templates inside of templates, which means that every time the outer template is rendered, you recompile the inner template, which is unnecessary and negates most of Underscore.js' rendering speed advantage. Fixing this is discussed toward the end.


Deal with groups of items, not index math

Now, on to the meat of the question. I think the biggest code smell here is the modulo arithmetic, i.e. &lt;% if(index % limit == 0 ) { %&gt; et al. This works, but it's hard to read. Instead, we can make the code match our intent: We want tables with 3 records each, so let our code deal with the data in groups of 3. This saves us from having to do arithmetic on their indexes—or worring about their indexes at all. Changing only the #recourseParameterTemp template, we have this:

&lt;script type="text/template" id="recourseParameterTemp"&gt;
    &lt;% var group %&gt;
    &lt;% while(group = recourseParameter.splice(0, limit), group.length) { %&gt;
        &lt;%= _.template($('#header').html())({ "parameterCode": parameterCode }) %&gt;

        &lt;% _.each(group, function (item, index) { %&gt;
            &lt;% if(item.description) { %&gt;
                &lt;tr&gt;
                    &lt;td colspan=5&gt;&lt;%= item.description %&gt;&lt;/td&gt;
                &lt;/tr&gt;
            &lt;% } %&gt;

            &lt;% if(recourseParameter.length) { %&gt;
                    &lt;%= _.template($('#closer').html())() %&gt;
                    &lt;span&gt;Continue ... &lt;/span&gt; 
                &lt;/div&gt;
            &lt;% }  %&gt;
        &lt;% }) %&gt;
    &lt;% } %&gt;
    &lt;%= _.template($('#footer').html())() %&gt;
&lt;/script&gt;


Here's a fiddle of it in action.

I think further improvements are possible, however. For one thing, why is &lt;div id="recourseParameter"&gt; inside a sub-template, but &lt;/div&gt; is inside the main template? Not only is this an odd inconsistency, it actually introduced the missing &lt;/div&gt; bug mentioned above. We can fix this by moving &lt;span&gt;Continue...&lt;/span&gt; and &lt;/div&gt; into the #closer template, and also adding &lt;/div&gt; to the #footer template (see this fiddle), but the bug points to a more general code smell: Templates with no closing tags, or no opening tags. If a template closes all of the tags it opens, it's much easier to notice problems like our missing &lt;/div&gt;.

The single responsibility principle

We usually talk about the single responsibility principle as it relates to object-oriented programming, but it's very useful here, too: Our templates are meant to isolate blocks of code that are related, and a great template has a single responsibility. Our #recourseParameterTemp template has a bunch of responsibilities—it iterates through the data, it decides whether or not to render each &lt;tr&gt;, and it decides what kind of footer render. That's too much! Using this principle, a number of possible improvements reveal themselves.

In my changes, I introduced an additional loop, i.e. I put a while around the _.each. This makes it a little harder to read, but also reminds us that it's often good to extract the inside of a loop into a sub-template that has a single responsibility. Extracting the inside of the while loop into a template called #groupTmpl (along with the #closer/#footer changes mentioned above) gives us this:

&lt;script type="text/template" id="groupTmpl"&gt;
    &lt;%= _.template($('#header').html())({ parameterCode: parameterCode }) %&gt;

    &lt;% _.each(group, function (item, index) { %&gt;
        &lt;% if(item.description) { %&gt;
            &lt;tr&gt;&lt;td colspan=5&gt;&lt;%= item.description %&gt;&lt;/td&gt;&lt;/tr&gt;
        &lt;% } %&gt;
    &lt;% }) %&gt;
    &lt;% if(recourseParameter.length) { %&gt;
        &lt;%= _.template($('#closer').html())() %&gt;
    &lt;% } else { %&gt;
        &lt;%= _.template($('#footer').html())() %&gt;
    &lt;% } %&gt;
&lt;/script&gt;

&lt;script type="text/template" id="recourseParameterTmpl"&gt;
    &lt;% var group %&gt;
    &lt;% while(group = recourseParameter.splice(0, limit), group.length) { %&gt;
        &lt;%= _.template( $('#groupTmpl').html() )( {
                recourseParameter: recourseParameter,
                parameterCode: parameterCode,
                group: group } ) %&gt;
    &lt;% } %&gt;
&lt;/script&gt;


Our intent has become clearer. We see that #recourseParameterTmpl's single responsibility is to render a sub-template (#groupTmpl) once for each group, and that's all it does. This makes it easier to see the intent of the rest of the code, now in #groupTmpl. It also makes it easier to see that #groupTmpl still has multiple responsibilities: It renders the #header sub-template, it loops through each item in group, and it decides what kind of footer to render.

(You probably also noticed that I changed #recourseParamaterTemp to #recourseParameterTmpl; I did this just because "temporary" is frequently shortened to "temp" in programming; "tmpl" is less ambiguous.)

One footer template

We could extract the inside of the _.each loop into a sub-template, but I think we can agree that that's probably overkill. The main thing we can improve here is that #groupTmpl is deciding what kind of footer to render, but that shouldn't be its responsibility. Instead, we should just render one template, and let that template decide what the footer should look like. Looking at our existing #closer and #footer templates, we can see that they're almost identical, except for the contents of &lt;span&gt;. It makes sense to consolidate these into one template. Removing #closer entirely, #footer and #groupTmpl now look like this (here's the fiddle):

&lt;script type="text/template" id="footer"&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
        &lt;span&gt;
            &lt;%= recourseParameter.length ? "Continue..." : "All are done" %&gt;
        &lt;/span&gt;
    &lt;/div&gt;
&lt;/script&gt;

&lt;script type="text/template" id="groupTmpl"&gt;
    &lt;%= _.template($('#header').html())({ parameterCode: parameterCode }) %&gt;

    &lt;% _.each(group, function (item, index) { %&gt;
        &lt;% if(item.description) { %&gt;
            &lt;tr&gt;&lt;td colspan=5&gt;&lt;%= item.description %&gt;&lt;/td&gt;&lt;/tr&gt;
        &lt;% } %&gt;
    &lt;% }) %&gt;

    &lt;%= _.template($('#footer').html())({ recourseParameter: recourseParameter }) %&gt;
&lt;/script&gt;


Now #groupTmpl's intent is very clear, and we don't have any duplicated footer code.

Self-contained templates close their own tags

This is looking pretty good, but we still have the problem I mentioned above: #header opens tags that it doesn't close, and #footer closes tags that it doesn't open.

An alternative is to combine those templates into a single #wrapper template. Since Underscore.js templates don't have good support for "nested" templates, this gets a little hairy, unless we do one simple thing—which we ought to do anyway: Initialize the sub-template functions outside of the template itself. Instead of doing this:

&lt;%= _.template($('#groupTmpl').html())( ... ) %&gt;


We should do this, in our JavaScript:

var groupTmpl = _.template( $('#groupTmpl').html() );


...for each of our templates, and then pass the compiled template functions as locals when we use a template, which will allow us to do this in a template:

&lt;%= groupTmpl( ... ) %&gt;


In addition to looking cleaner, this avoids recompiling the sub-template every time the (outer) template is compiled, as mentioned above.

Along with this, instead of passing around a bunch of variables (recourseParameter, parameterCode, etc.) among our templates, it's probably a good idea to use the variable option to _.template. That is, when we call var tmpl = _.template(html, { variable: 'locals' }), then render it with tmpl({ foo: "bar" }), foo will be available as locals.foo inside the template, instead of just foo. While this seems less convenient, it lets us just pass locals to sub-templates instead of specifying the whole object. Instead of passing { variable: 'locals' } every time we compile a template, though, we can set it globally using _.templateSettings.variable = 'locals'.

Finally...

...we end up with templates that look like this:

&lt;script type="text/template" id="wrapperTmpl"&gt;
    &lt;div id="recourseParameter"&gt;
        &lt;h1&gt;Parameter : &lt;%= locals.parameterCode %&gt;&lt;/h1&gt;
        &lt;table&gt;
            &lt;thead&gt;
                &lt;tr&gt;&lt;th colspan=5&gt;header&lt;/th&gt;&lt;/tr&gt;
            &lt;/thead&gt;
            &lt;tbody&gt;
                &lt;%= locals.bodyTmpl(locals) %&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
        &lt;span&gt;
            &lt;%= locals.recourseParameter.length ? "Continue..." : "All are done" %&gt;
        &lt;/span&gt;
    &lt;/div&gt;
&lt;/script&gt;

&lt;script type="text/template" id="groupTmpl"&gt;
    &lt;% _.each(locals.group, function (item, index) { %&gt;
        &lt;% if(item.description) { %&gt;
            &lt;tr&gt;&lt;td colspan=5&gt;&lt;%= item.description %&gt;&lt;/td&gt;&lt;/tr&gt;
        &lt;% } %&gt;
    &lt;% }) %&gt;
&lt;/script&gt;

&lt;script type="text/template" id="recourseParameterTmpl"&gt;
    &lt;% locals = _.defaults({ bodyTmpl: locals.groupTmpl }, locals) %&gt;
    &lt;% while(locals.group = locals.recourseParameter.splice(0, locals.limit), locals.group.length) { %&gt;
        &lt;%= locals.wrapperTmpl( locals ) %&gt;
    &lt;% } %&gt;
&lt;/script&gt;


And JavaScript that looks like this:

_.templateSettings.variable = "locals";

var tmpl = _.template( $('#recourseParameterTmpl').html() ),
    locals = {
        limit: 3,
        parameterCode: "foo",
        recourseParameter: [
            { description: "Foo 1" },
            // ...
        ]
    },
    renderedTmpl
;

locals.wrapperTmpl = _.template( $('#wrapperTmpl').html() );
locals.groupTmpl   = _.template( $('#groupTmpl').html() );
// You could also automate the above with jQuery, e.g.:
//
//     $("[type='text/template']").each(function() {
//       var el = $(this), id = el.attr('id');
//       locals[id] = _.template( el.html() );
//     });

renderedTmpl = tmpl(locals)

$('body').append(renderedTmpl)


Here's the final fiddle. I hope that's helpful!