LoginSignup
18
8

More than 5 years have passed since last update.

【Go言語】GinでTemplateパッケージにCSS等のファイルを適用させる

Last updated at Posted at 2019-02-04

背景

Webの画面をGoで作りたく、ただ、フルスタックのBeegoを入れるほどリッチにはしたくないなと、ってことでGinをいれて作っていた。
※紛らわしいことにコンパイルのauto-reloadをやってくれる同名のGINというパッケージもある

ここでは、CSS等をhtmlに適用させる際に学んだことをつらつら書いていきたいと思います。

CSSを適用させる

main.goがあったとする。というより、こう書けば静的ファイルをインポートできる。

main.go
package main

import "github.com/gin-gonic/gin"

func main() {
        r := gin.Default()
        // 静的ファイルの
        // router.Static("URL", "静的ファイル格納場所")
        router.Static("/assets", "./assets")
        router.LoadHTMLGlob("templates/*/**")        
        HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "XXX",
        })
        r.Run()
}

ちなみにフォルダ構成はこんな感じ

root/
 ├ main.go
 ├ templates/main/index.tmpl
 | // ここに静的ファイルを置く
 └ assets/
    ├ images/xxx.png
    └ css/xxx.css

んで、テンプレート

(index.tmpl).html
//↑.htmlって書かないとQiitaのスタイルが適用されないので...
<html>
<head>
    <title>{{.title}} </title>
    <style type="text/css" media="screen">
      @import url("/assets/css/xxx.css");
    </style>
</head>
<body>
    <h1>TEST</h1>
</body>
</html>
18
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
8