'How can I Inline JS/CSS in a Go template?
I have a go template like https://github.com/kaihendry/ltabus/blob/master/static/index.html
What is my best strategy to inline CSS/JS on compilation?
E.g. on execution I want <link rel='stylesheet' href='/static/style.css'> to become:
<style>
body {
padding: 5px;
font-size: 120%;
} ... /* and so forth */
</style>
Perhaps I should have a build step / Makefile?
Solution 1:[1]
As I mentioned in comments you can compile it with webpack plugin which change link to the real file content.
But if you want to do it with go-template you can directly inject css to your html file
index.html
<style>
{{.Style}}
</style>
in your go file
tmpl, err := template.New("index.html").ParseFiles("index.html")
if err != nil {
// handle error
return
}
style, err := os.ReadFile("style.css")
if err != nil {
// handle error
return
}
tmplData := struct {
Style template.CSS
}{Style: template.CSS(style)}
err = tmpl.Execute(os.Stdout, tmplData)
if err != nil {
// handle error
return
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | isavinof |
