LoginSignup
0
0

More than 5 years have passed since last update.

Dividing template files for layout and content at Golang

Posted at

Environmnet

go version go1.11.5 linux/amd64

Directory Structure

/go
 └ src/
   └ sample/
     └ main.go
     └ templates/
       └ layout.html
       └ top.html

Source code

main.go
package main

import(
        "html/template"
        "log"
        "net/http"
)

func handlerIndex(w http.ResponseWriter, req *http.Request) {

        t := template.Must(template.ParseFiles(
                "templates/layout.html",
                "templates/top.html",
        ))

        s := "world"
        e := t.ExecuteTemplate(w, "layout.html", s)
        if e != nil { log.Fatal(e) }
}

func main() {
        http.HandleFunc("/", handlerIndex)
        http.ListenAndServe(":8080", nil)
}
templates/layout.html
<!DOCTYPE html>
<html>
        <body>
                {{ template "top.html" . }}
        </body>
</html>
templates/top.html
Hello, {{ . }}.

Build & Run

cd $GOPATH/src/sample/ && go run main.go

スクリーンショット 2019-02-17 13.27.48.png

0
0
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
0
0