简体   繁体   English

如何在 Go 模板中内联 JS/CSS?

[英]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我有一个 go 模板,例如https://github.com/kaihendry/ltabus/blob/master/static/index.html

What is my best strategy to inline CSS/JS on compilation?在编译时内联 CSS/JS 的最佳策略是什么?

Eg on execution I want <link rel='stylesheet' href='/static/style.css'> to become:例如,在执行时我希望<link rel='stylesheet' href='/static/style.css'>变成:

<style>
body {
padding: 5px;
font-size: 120%;
} ... /* and so forth */
</style>

Perhaps I should have a build step / Makefile?也许我应该有一个构建步骤/Makefile?

As I mentioned in comments you can compile it with webpack plugin which change link to the real file content.正如我在评论中提到的,您可以使用 webpack 插件对其进行编译,该插件会将链接更改为真实文件内容。

But if you want to do it with go-template you can directly inject css to your html file但是如果你想用 go-template 来做,你可以直接将 css 注入到你的 html 文件中

index.html index.html

<style>
  {{.Style}}
</style>

in your go file在您的 go 文件中

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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