Go Templates

Descripcion general

gpdf se integra con el paquete text/template de Go para la generacion de contenido dinamico. Los templates producen salida de esquema JSON que gpdf renderiza como PDF.

Hay dos enfoques disponibles:

  1. FromJSON — Expresiones de Go template en linea dentro de JSON (mas simple)
  2. FromTemplate — Go template preparsado para control total (flexible)

FromJSON con expresiones de template

El enfoque mas simple — integre expresiones de Go template directamente en 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 con templates preparsados

Para logica compleja como bucles y condicionales, use 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.                                │
│                                                   │
└───────────────────────────────────────────────────┘

Mapa de funciones de template

Use TemplateFuncMap() al parsear templates — proporciona funciones auxiliares:

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

Funciones disponibles

FuncionDescripcion
toJSONConvierte un valor de Go a cadena JSON (util para incrustar datos)

Secciones dinamicas con Range

Itere sobre datos para generar secciones repetidas:

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

Condicionales

Use if para contenido condicional:

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

Consejos

  • Use {{- y -}} para recortar espacios en blanco alrededor de las acciones del template
  • Maneje las comas JSON con cuidado en los bucles range (use {{if $i}},{{end}})
  • Use TemplateFuncMap() para obtener funciones auxiliares integradas
  • Las opciones de Go (WithFont, WithMargins, etc.) pueden sobrescribir la configuracion del template:
doc, err := template.FromTemplate(tmpl, data,
    template.WithFont("NotoSansJP", fontData),
    template.WithDefaultFont("NotoSansJP", 12),
)