[go] 템플릿 파일 저장

이번 포스팅에서는 Go 언어를 사용하여 템플릿 파일을 저장하는 방법에 대해 알아보겠습니다.

1. 템플릿 파일 만들기

먼저, 원하는 형식의 템플릿 파일을 생성합니다. 예를 들어, template.html이라는 이름의 HTML 템플릿 파일을 만들 수 있습니다.


<!DOCTYPE html>
<html>
<head>
    <title>{{.Title}}</title>
</head>
<body>
    <h1>{{.Header}}</h1>
    {{range .Items}}<p>{{.}}</p>{{end}}
</body>
</html>

위의 예제 코드는 Go 템플릿에 사용할 수 있는 간단한 HTML 구조를 보여줍니다. .Title, .Header, .Items는 템플릿에 삽입될 데이터를 나타냅니다.

2. 템플릿 파일 저장

이제 Go 언어를 사용하여 템플릿 파일을 읽고 저장하는 방법을 살펴보겠습니다.

package main

import (
    "fmt"
    "html/template"
    "os"
)

func main() {
    data := struct {
        Title  string
        Header string
        Items  []string
    }{
        "My Page",
        "Welcome to My Page",
        []string{"first item", "second item", "third item"},
    }

    tmpl, err := template.New("page").ParseFiles("template.html")
    if err != nil {
        fmt.Println("Error parsing template:", err)
        return
    }

    out, err := os.Create("index.html")
    if err != nil {
        fmt.Println("Error creating file:", err)
        return
    }
    defer out.Close()

    err = tmpl.Execute(out, data)
    if err != nil {
        fmt.Println("Error executing template:", err)
    }
    fmt.Println("File created successfully!")
}

위의 예제 코드에서는 template.New() 함수를 사용하여 새 템플릿을 생성하고, ParseFiles() 함수를 사용하여 템플릿 파일을 파싱합니다. 그리고 Execute() 함수로 데이터를 삽입하여 최종 HTML 파일을 생성합니다.

이제 Go 언어를 사용하여 템플릿 파일을 저장하는 방법에 대해 알아보았습니다.

더 많은 정보를 원하신다면 Go 템플릿 문서를 참고하시기 바랍니다.