Table striped effect

Is there any way how to achieve this efect on DataGrid panel (class=“table table-striped”) ?

2019-07-08_18h51_22

1 Like

I thought about this once and used this:

def color_alternating_rows(self):
    for i, r in enumerate(self.repeating_panel_1.get_components()):
      if i%2:
        r.background='theme:Gray 200'

I put that method on the “parent” form and call it from the template form on the “show” event (this way when you scroll through the data grid’s pages, the row highlighting is applied when the new page is shown).

Probably better ways, but it’s short and sweet-ish.

3 Likes

I tend to modify the dict array that I pass to items. Some python experts will be able to improve on my rather long winded and haphazard code (and indeed they have done!), but I create a “client_tools” module containing utility functions like this :

# Edited to reflect a better technique demonstrated by @p.colbert 
# (& @campopianoa  though I didn't recognise it at the time).
def zebra(data):
  for counter, d in enumerate(data):
    d['shade']=True if counter % 2 else False

Then do this in the form containing the repeating_panel :

include client_tools
...
self.repeating_panel_1.items = client_tools.zebra(data)

Then in the line items form, I do this :

if self.item.get("shade",False):
  self.background = "#eee"
3 Likes

You’re going to love enumerate:
for counter, d in enumerate(data):

3 Likes

campopianoa’s solution worked out of the box for me, but I would like to try your version also.

I can not get over the last part:

if self.item.get("shade",False):
  self.background = "#eee"

Could you please point me in the right direction ?
Sorry just beginner here…thanks !

These approaches are a great way to do this from Python. If you don’t mind meddling with the CSS, you can also do this by adding a rule to theme.css in Assets:

.anvil-data-grid .anvil-data-row-panel:nth-child(even) {
  background-color: #eee;
}
7 Likes

Sure. Not sure which bit so here’s a full-ish explanation…
The dictionary property self.item in the item line form contains one record of data, which anvil passes to it upon creation (ie when you do this : self.repeating_panel_1.items = mydictarray)

The zebra function I showed adds a field to the record (“shade”), and the code above checks to see if it is present in the dictionary that was passed and sets its own background colour to create the stripe if it is.

You could rewrite that code in longhand as :

if "shade" in self.item:
  if self.item["shade"] == True:
    self.background = "#eee"

Here’s info on the dictionary “get” method :
https://www.tutorialspoint.com/python/dictionary_get.htm

1 Like