在 Go 模板中如何嵌入 JavaScript 和 CSS?

时间:2024-03-10

浏览:209

作者:佚名

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《在 Go 模板中如何嵌入 JavaScript 和 CSS?》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我有一个像 https://github.com/kaihendry/ltabus/blob/master/static/index.html 这样的 go 模板

在编译时内联 css/js 的最佳策略是什么?

例如执行时我希望 <link rel='stylesheet' href='/static/style.css'> 变为:

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

也许我应该有一个构建步骤/makefile?


正确答案


正如我在评论中提到的,您可以使用 webpack 插件来编译它,该插件会更改指向真实文件内容的链接。

但是如果你想使用 go-template 来做到这一点,你可以直接将 css 注入到你的 html 文件中

index.html

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

在你的 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
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在 Go 模板中如何嵌入 JavaScript 和 CSS?》文章吧,也可关注golang学习网公众号了解相关技术文章。

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页