Using image/color to fill table cells in HTML template

What is the best way to Go about this:

import (
	"image/color"
)

type Week struct {
	WeekName  string
	WeekValue int
}

type Row struct {
	Weeks                                                                             []Week
}

func generateTable() []Row {

	rows := []Row{
		{
			Weeks: []Week{
				Week{WeekName: "01", WeekValue: color.RGBA{240, 248, 255, 255},
				Week{WeekName: "02", WeekValue: 0},
				Week{WeekName: "03", WeekValue: 1},
				Week{WeekName: "04", WeekValue: 0},
				Week{WeekName: "05", WeekValue: 0},
				Week{WeekName: "06", WeekValue: 0},
				Week{WeekName: "07", WeekValue: 1},
				Week{WeekName: "08", WeekValue: 0},
				Week{WeekName: "09", WeekValue: 1},
				Week{WeekName: "10", WeekValue: 0},

				Week{WeekName: "CW01", WeekValue: 1},
				Week{WeekName: "CW02", WeekValue: 0},
			},
		},

I would like to make it so that if the WeekValue = “1” then fill the table cell with a colour (same colour for all)

Here’s a bit of my HTML:

<table>
        {{range .ObjectMap.Table}}
	        <tr align="center">
	            {{range .Weeks}}
	            	<td>{{.WeekValue}}</td>
	            {{end}}
	        </tr>
		{{end}}
</table>

Any help is very much appreciated.

Hey @lennybeadle,

I personally think it would be better to just use something like this rather than passing color.RGBA values into the template: https://play.golang.org/p/xBEBHZpRbJ.

However if you do want to pass those values in as color.RGBA objects, you can always create a FuncMap along with your template and then use that to work out what to write in your html code.

You could also change the Week struct I demonstrated to contain a string called Color which you can then use in your template if you need to constantly change Week's color values.

2 Likes

Thanks @radovskyb for the solution, it works!!

Although now I have other issues:

  • I’d like it to actually fill the table cell with colour, without any text.
  • I tried to do “bgcolor” instead however it doesn’t work because maybe it’s conflicting with my styles.css as my table already has some colour to it.

Any ideas?

Big thanks!

********* EDIT **********

Okay I’ve managed actually xD

{{range .}}
    {{if eq .WeekValue 0 }}
           	<td>{{.WeekValue}}</td>
               {{else}}
              <td bgcolor="green";>&nbsp;</td>
           {{end}}
   {{end}}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.