Alternating styles in DataView
A few months ago, I showed how you can alternate styles using CSS in a server-side ListView, by selecting the class depending on the remainder of the division of the data index by two.
Well, you can do the exact same thing with the client-side DataView.
Let’s first define the classes we’ll want to apply to the even and odd rows:
tbody tr { background-color: #f0f0f0; } tbody tr.odd { background-color: #c0c0c0; }
Then, we can use the class namespace to bind the presence of a CSS class to a Boolean condition:
<tr class:odd="{{ $index % 2 }}">
Within the context of the template, $index is the index of the current data item, so $index % 2 will be evaluated as 1 and 0 alternatively. For JavaScript, when evaluated in a Boolean context, these are equivalent to true and false, so the class “odd” will be alternatively present and absent from the rows.
Here’s the complete template:
<table> <thead><tr><td>Name</td><td>Age</td></tr></thead> <tbody id="peopleIKnow"
sys:attach="dataview" class="sys-template"> <tr class:odd="{{ $index % 2 }}"> <td>{{ name }}</td> <td>{{ age }}</td> </tr> </tbody> </table>
And here’s what the rendering looks like:
The full source code for the page can be found here and uses Microsoft Ajax 4.0 Preview 3:
http://weblogs.asp.net/blogs/bleroy/Samples/TemplateAlternating.htm.txt