Html and CSS with html/template in Go
While building a small app to generate static html files I found myself using the
html/template
library. While trying to embed some CSS from a shared file I found that I ran into the ZgotmplZ
issue.
In short, my simple template didn’t work as expected. For example:
<style>
{{.Style }}
</style>
Would output <style>ZgotmplZ</style>
instead of the css I had asked for. I found some hints on
stackoverflow
and I found myself wanting to document my findings so I can remember what I did when I wake up tomorrow.
To keep things short, I created a template function safeCss
for to help me out. Here is a snippet of my solution:
package main
import (
"bytes"
_ "embed"
"fmt"
"html/template"
)
//go:embed html/index.html
var html string
//go:embed html/style.css
var css string
type Model struct {
Style string
}
func main() {
model := Model{
Style: css,
}
funcs := template.FuncMap{
"safeCss": func(s string) template.CSS {
return template.CSS(s)
},
}
template, err := template.New("index").Funcs(funcs).Parse(html)
if err != nil {
panic(err)
}
var output bytes.Buffer
err = template.Execute(&output, model)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", output.String())
}
The html markup would render the variable using this syntax:
<style>
{{.Style | safeCss }}
</style>
Feel free to download and run the full demo locally .