开发者

Better way to Handle No Results Row with Jquery Templates

I am using JQuery templates and want to generate a single row that says "no results found" if there are no results in the array that gets sent to the template. The way I handle it now is to have two templates - one that outputs the rows and another with output for the no rows exist instance, but this seems dirty to me. Are there better ways to handle this situation?

if(results.length == 0)
   $( "#NoRowsTemplate" ).tmpl( results ).appen开发者_如何学编程dTo("#tableid")
else
   $( "#HasRowsTemplate" ).tmpl( new Array(1)).appendTo("#tableid")

Here is a sample of the template with rows:

<script id="HasRowsTemplate" type="text/x-jquery-tmpl">
<tr>
<td>${name}</td>
</tr>
</script>

And here is a sample of the template without rows:

<script id="NoRowsTemplate" type="text/x-jquery-tmpl">
<tr>
<td>No Rows Were Found</td>
</tr>
</script>


You can use {{if}} and {{else}}.

It's hard to tell more without actually seeing the template in question.

Update:

Ok, you posted some examples so I can say more now. First of all, where is the rest of your table? Why is it not in the template? The raws are appended to an existing table but I assume this is done only once because otherwise you wouldn't append the "No Rows Were Found" message to the table, but you would replace the existing content.

First of all in this particular case you might use a quick hack and just use:

if (results.length === 0) {
    results = ["No Rows Were Found"];
}
$( "#NoRowsTemplate" ).tmpl( results ).appendTo("#tableid");

and it should just do what you want but I wouldn't recommend this method because it changes the array and may cause some problems in other parts of your code. I would recommend doing something like this:

$( "#newTemplate" ).tmpl({ results: results }).appendTo("#tableid");

with this new template:

<script id="newemplate" type="text/x-jquery-tmpl">
  {{if results.length}}
    {{each results}}
      <tr>
        <td>${value}</td>
      </tr>
    {{/each}}
  {{else}}
    <tr>
      <td>No Rows Were Found</td>
    </tr>
  {{/if}}
</script>

and I would also add the rest of the table HTML to the very beginning and the very end of this template.


One option is to wrap the array in an anonymous object, so that the template is not called for each item in the array, then you can use a conditional statement ( {{if}} ) to check for the length and use {{each}} to loop through the items.

So, pass it like: $("#Template").tmpl({ items: results }).appendTo("#tableid")

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜