Search code examples
htmlhtml-tablemustache

Only Create Table when it has rows of data


If I have a simple table:

<table>
<TR><TH>First Name</TH><TH>Last Name</TH></TR>
<TR><TD>John</TD><TD>Smith</TD></TR>
<TR><TD>Sponge</TD><TD>Bob</TD></TR>
</TABLE>

I can load it in MustacheJS with something like:

<Table>
<TR><TH>First Name</TH><TH>Last Name</TH></TR>
{{#loop}}
<TR><TD>{{fname}}</TD><TD>{{lname}}</TD></TR>
{{/loop}}
</TABLE>

And it works properly with data in the format of:

{ loop: [{fname:"John", lname:"Smith"},{fname:"Sponge", lname:"Bob"}]}

But how do the same thing but ONLY have the table show at all if there are rows of data? If I move the #loop to surround the table, it creates multiple tables per row.


Solution

  • You can achieve this by adding an additional property to your data that will return a boolean based on the length of your data to loop. Then add a section to your template to display the table based on this new property.

    Data:

    var data = {
      loop: [
        { fname: "John", lname: "Smith" },
        { fname: "Sponge", lname: "Bob" }
      ],
      shouldLoop() { return this.loop.length > 0 }
    };
    

    Template:

    {{#shouldLoop}}
    <Table>
    <TR><TH>First Name</TH><TH>Last Name</TH></TR>
    {{#loop}}
    <TR><TD>{{fname}}</TD><TD>{{lname}}</TD></TR>
    {{/loop}}
    </TABLE>
    {{/shouldLoop}}