8

I have a simple Go / Gin web app. I need to put some dynamic content in html template.

For e.g. I have a few tables (the number is dynamic) with a few rows (the number is dynamic). I need to put them in html template. Is there any way to combine templates in code? I'd prefer to use templates rather than build tables in the code.

I've checked a tutorial https://github.com/gin-gonic/gin but it is not covered there.

kikulikov
  • 2,512
  • 4
  • 29
  • 45

1 Answers1

6

You can use define to define partials and template to mix multiple HTML partials.

package main

import (
    "html/template"

    "github.com/gin-gonic/gin"
)

var (
    partial1 = `{{define "elm1"}}<div>element1</div>{{end}}`
    partial2 = `{{define "elm2"}}<div>element2</div>{{end}}`
    body     = `{{template "elm1"}}{{template "elm2"}}`
)

func main() {
    // Or use `ParseFiles` to parse tmpl files instead 
    t := template.Must(template.New("elements").Parse(body))

    app := gin.Default()
    app.GET("/", func(c *gin.Context) {
        c.HTML(200, "elements", nil)
    })
    app.Run(":8000")
}

This is a good place to read https://gohugo.io/templates/go-templates/

Pandemonium
  • 7,724
  • 3
  • 32
  • 51
  • Thank you! The resource is really useful. – kikulikov Jun 14 '16 at 14:36
  • 1
    Another useful resource is https://golang.org/pkg/text/template/ — that's the official documentation for templates. It's not as well done as what @pie-oh-pah posted, but at least it's clear what is part of the 'official' documentation, and what is specific to `Hugo`. – Gwyneth Llewelyn Jun 08 '20 at 12:43