Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use templates in Go Gin for dynamic content

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.

like image 236
kikulikov Avatar asked Jun 14 '16 13:06

kikulikov


1 Answers

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/

like image 142
Pandemonium Avatar answered Sep 22 '22 07:09

Pandemonium