[go] 템플릿 동적 생성

Go 언어에는 HTML 템플릿을 사용하여 동적 콘텐츠를 생성하는 여러 가지 방법이 있습니다. 이 포스트에서는 Go의 내장 템플릿 엔진인 html/template 패키지를 사용하는 방법을 살펴보겠습니다.

1. html/template 패키지 설치

먼저 html/template 패키지를 설치합니다.

import "html/template"

2. 템플릿 작성

동적 콘텐츠를 생성하기 위한 템플릿을 작성합니다.


const tmpl = `<!DOCTYPE html>
<html>
<head>
    <title>{{.Title}}</title>
</head>
<body>
    <h1>{{.Heading}}</h1>
    <p>{{.Content}}</p>
</body>
</html>`

3. 데이터 바인딩

템플릿에 데이터를 바인딩하여 HTML을 렌더링합니다.

type Page struct {
    Title   string
    Heading string
    Content string
}

func main() {
    p := Page{
        Title:   "Dynamic Content",
        Heading: "Welcome to Dynamic Content",
        Content: "This is a dynamic content example using Go templates.",
    }

    t := template.New("webpage")
    t, _ = t.Parse(tmpl)
    t.Execute(os.Stdout, p)
}

위의 코드는 html/template 패키지를 사용하여 동적 콘텐츠를 생성하는 간단한 예제입니다.

Go 언어를 사용하여 html/template 패키지로 동적 콘텐츠를 생성하는 방법은 이렇게 간단합니다.

참고 자료