Skip to content

Go:text/template

Package template implements data-driven templates for generating textual output.

Example

package main

import (
    "os"
    "text/template"
)

// Data structure / 데이터 구조체
type Person struct {
    Name string
    Comm string  // Comment field / 코멘트 필드
    Age  int
}

func main() {
    // Template definition / 템플릿 정의
    tmpl := `
Name: {{.Name}}
Comment: {{.Comm}}
Age: {{.Age}}
`

    // Parse template / 템플릿 파싱
    t, err := template.New("person").Parse(tmpl)
    if err != nil {
        panic(err)
    }

    // Data to inject / 주입할 데이터
    person := Person{
        Name: "홍길동",
        Comm: "안녕하세요",
        Age:  30,
    }

    // Execute template / 템플릿 실행
    err = t.Execute(os.Stdout, person)
    if err != nil {
        panic(err)
    }
}

다음과 같이 출력됨:

Name: 홍길동
Comment: 안녕하세요
Age: 30

주요 템플릿 액션들:

{{.Field}}           // Field access / 필드 접근
{{.Method}}          // Method call / 메서드 호출
{{if .Condition}}    // Conditional / 조건문
{{range .Items}}     // Loop / 반복문
{{with .Value}}      // Context change / 컨텍스트 변경
{{/* comment */}}    // Comment / 주석

See also

Favorite site