1

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?

2
  • If I got you correct, you can use webpack for this webpack.js.org/loaders/style-loader Commented May 5, 2022 at 9:50
  • go template isnt really meant for this. It's not a bundler or something like webpack. In a nutshell its there to substitute placeholder variables in a blob of text with values from a context. It wont substitue links with content. You need to provide the content of the file that should go between the style tags yourself and template it accordingly, or use someting lese. Commented May 5, 2022 at 11:02

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.