简体   繁体   中英

Prawn set cell color under a condition while making a table

I'm trying to generate a table while changing the background color of a cell under a condition. I've resorted coming to here for help. Here's an example of what I'm trying to do:

        idx = 0 

        pdf.table(myTable) do
            style(row(0), :background_color => 'ff00ff')
            style(column(0))
            while idx <= totalRows
                if cells[idx,3] == "No go"
                    style(cells[idx,3], :background_color => 'fF0000')
                else 
                    style(cells[idx,3], :background_color => '00FF22')
                end 
            idx += 1 
            end 
          
        end

Call #style correctly

In version 0.2.2 of prawn-table, the #style method is defined on a cell, or an array of cells, so you need to get that first. The argument is merely a hash of the keys and values for the styles you want. For example, row(0) is an array of cells, so you can style it with a magenta background like this:

  pdf.table(myTable) do        
    row(0).style(:background_color => 'ff00ff')
  end

示例表的第一行具有洋红色背景

You can refer to the full source code of #style at

column(0)

I am not sure what you want the line style(column(0)) to do, so I can't advise on that.

Condition when "No go"

It looks like you want the while loop to apply a condition to the fourth column, so that cells whose content is 'No go' are red, while the rest are green.

For this, you can use the iterator built-in to the #style method, instead of your while loop. It could look like this:

    column(3).style do |cell|
       if cell.content == "No go"
         cell.style(:background_color => 'ff0000')
       else
         cell.style(:background_color => '00ff22')
       end
    end

column(3) 的样式基于条件

If you wanted something slightly different you should know enough now to vary the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM