英文:
Only Create Table when it has rows of data
问题
如果我有一个简单的表格:
<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>
我可以在MustacheJS中这样加载它:
<Table>
<TR><TH>First Name</TH><TH>Last Name</TH></TR>
{{#loop}}
<TR><TD>{{fname}}</TD><TD>{{lname}}</TD></TR>
{{/loop}}
</TABLE>
并且它可以正常工作,数据格式如下:
{ loop: [{fname:"John", lname:"Smith"},{fname:"Sponge", lname:"Bob"}]}
但是如果我只想在有数据行时才显示表格,应该如何做呢?如果我将#loop
移动到包围整个表格,它会为每一行创建多个表格。
英文:
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.
答案1
得分: 2
你可以通过向数据添加一个附加属性来实现这一点,该属性将根据要循环的数据的长度返回一个布尔值。然后,根据这个新属性,向模板添加一个部分来显示表格。
数据:
var data = {
loop: [
{ fname: "John", lname: "Smith" },
{ fname: "Sponge", lname: "Bob" }
],
shouldLoop() { return this.loop.length > 0 }
};
模板:
{{#shouldLoop}}
<table>
<tr><th>First Name</th><th>Last Name</th></tr>
{{#loop}}
<tr><td>{{fname}}</td><td>{{lname}}</td></tr>
{{/loop}}
</table>
{{/shouldLoop}}
英文:
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}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论