Go 템플릿

개요

gpdf는 동적 콘텐츠 생성을 위해 Go의 text/template 패키지와 통합됩니다. 템플릿은 gpdf가 PDF로 렌더링하는 JSON 스키마 출력을 생성합니다.

두 가지 접근 방식을 사용할 수 있습니다:

  1. FromJSON — JSON에 Go 템플릿 표현식 인라인 삽입 (더 간단함)
  2. FromTemplate — 사전 파싱된 Go 템플릿으로 완전한 제어 (유연함)

FromJSON과 템플릿 표현식

더 간단한 접근 방식 — Go 템플릿 표현식을 JSON에 직접 삽입합니다:

schema := []byte(`{
    "page": {"size": "A4", "margins": "20mm"},
    "metadata": {"title": "{{.Title}}"},
    "body": [
        {"row": {"cols": [
            {"span": 12, "text": "{{.Title}}", "style": {"size": 24, "bold": true}}
        ]}},
        {"row": {"cols": [
            {"span": 12, "text": "Author: {{.Author}}"}
        ]}}
    ]
}`)

doc, err := template.FromJSON(schema, map[string]any{
    "Title":  "Monthly Report",
    "Author": "ACME Corp",
})

FromTemplate과 사전 파싱된 템플릿

루프나 조건부 같은 복잡한 로직에는 FromTemplate을 사용합니다:

import (
    gotemplate "text/template"
    "github.com/gpdf-dev/gpdf/template"
)

tmplStr := `{
    "page": {"size": "A4", "margins": "20mm"},
    "metadata": {"title": "{{.Title}}"},
    "body": [
        {"row": {"cols": [
            {"span": 12, "text": "{{.Title}}", "style": {"size": 24, "bold": true}}
        ]}},
        {"row": {"cols": [
            {"span": 12, "spacer": "5mm"}
        ]}},
        {{- range $i, $section := .Sections}}
        {{- if $i}},{{end}}
        {"row": {"cols": [
            {"span": 12, "elements": [
                {"type": "text", "content": "{{$section.Heading}}", "style": {"size": 16, "bold": true, "color": "#1A237E"}},
                {"type": "spacer", "height": "3mm"},
                {"type": "text", "content": "{{$section.Body}}"},
                {"type": "spacer", "height": "8mm"}
            ]}
        ]}}
        {{- end}}
    ]
}`

tmpl, err := gotemplate.New("report").Funcs(template.TemplateFuncMap()).Parse(tmplStr)
if err != nil {
    log.Fatal(err)
}

type section struct {
    Heading string
    Body    string
}

data := map[string]any{
    "Title": "Quarterly Report - Q1 2026",
    "Sections": []section{
        {
            Heading: "Executive Summary",
            Body:    "Revenue increased 25% year-over-year, driven by new enterprise offerings.",
        },
        {
            Heading: "Product Development",
            Body:    "The gpdf library reached v0.8 with JSON schema and Go template support.",
        },
        {
            Heading: "Market Analysis",
            Body:    "PDF generation market grows. Zero-dependency approach resonates with Go devs.",
        },
        {
            Heading: "Next Steps",
            Body:    "Focus on reusable components, fuzz testing, and v1.0 release.",
        },
    },
}

doc, err := template.FromTemplate(tmpl, data)
if err != nil {
    log.Fatal(err)
}
pdfData, err := doc.Generate()
┌─ A4 ──────────────────────────────────────────────┐
│                                                   │
│  Quarterly Report - Q1 2026      ← 24pt bold      │
│                                                   │
│  Executive Summary               ← 16pt bold blue │
│  Revenue increased 25% year-over-year, driven     │
│  by new enterprise offerings.                     │
│                                                   │
│  Product Development                              │
│  The gpdf library reached v0.8 with JSON schema   │
│  and Go template support.                         │
│                                                   │
│  Market Analysis                                  │
│  PDF generation market grows. Zero-dependency     │
│  approach resonates with Go devs.                 │
│                                                   │
│  Next Steps                                       │
│  Focus on reusable components, fuzz testing,      │
│  and v1.0 release.                                │
│                                                   │
└───────────────────────────────────────────────────┘

템플릿 함수 맵

템플릿을 파싱할 때 TemplateFuncMap()을 사용합니다 — 헬퍼 함수를 제공합니다:

tmpl, err := gotemplate.New("doc").Funcs(template.TemplateFuncMap()).Parse(tmplStr)

사용 가능한 함수

함수설명
toJSONGo 값을 JSON 문자열로 변환 (데이터 삽입에 유용)

Range를 사용한 동적 섹션

데이터를 순회하여 반복 섹션을 생성합니다:

{{- range $i, $item := .Items}}
{{- if $i}},{{end}}
{"row": {"cols": [
    {"span": 6, "text": "{{$item.Name}}"},
    {"span": 6, "text": "{{$item.Value}}", "style": {"align": "right"}}
]}}
{{- end}}

조건부

조건부 콘텐츠에 if를 사용합니다:

{{- if .ShowHeader}}
{"row": {"cols": [
    {"span": 12, "text": "{{.HeaderText}}", "style": {"size": 20, "bold": true}}
]}},
{{- end}}

  • {{--}}를 사용하여 템플릿 액션 주변의 공백을 제거합니다
  • range 루프에서 JSON 콤마를 주의 깊게 처리합니다 ({{if $i}},{{end}} 사용)
  • TemplateFuncMap()을 사용하여 내장 헬퍼 함수를 가져옵니다
  • Go 옵션 (WithFont, WithMargins 등)으로 템플릿 설정을 재정의할 수 있습니다:
doc, err := template.FromTemplate(tmpl, data,
    template.WithFont("NotoSansJP", fontData),
    template.WithDefaultFont("NotoSansJP", 12),
)