How to use templates in Go Gin for dynamic content
Asked Answered
V

1

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.

Vahe answered 14/6, 2016 at 13:11 Comment(0)
C
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/

Courser answered 14/6, 2016 at 14:6 Comment(2)
Thank you! The resource is really useful.Vahe
Another useful resource is 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.Gravure

© 2022 - 2024 — McMap. All rights reserved.