Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass just a variable (not a struct member) into text/html template. Golang

is there any way to pass just a variable (string, int, bool) into template. For example (something similar):

import (
    "html/template"
)

func main() {
    ....
    tmpl := template.Must(template.ParseFiles("templates/index.html"))
    mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
        varmap := map[string]interface{}{
            "var1": "value",
            "var2": 100,
        }
        tmpl.ExecuteTemplate(rw, "index", varmap)
    })

    // content of index.html
    {{define "index"}}
    {{var1}} is equal to {{var2}}
    {{end}}
}
like image 834
Timur Fayzrakhmanov Avatar asked Jan 15 '15 19:01

Timur Fayzrakhmanov


1 Answers

Yes just use the dot in front of it:

http://play.golang.org/p/7NXu9SDiik

package main

import (
    "html/template"
    "log"
    "os"
)

var tmplString = `    // content of index.html
    {{define "index"}}
    {{.var1}} is equal to {{.var2}}
    {{end}}
`

func main() {
    tmpl, err := template.New("test").Parse(tmplString)
    if err != nil {
        log.Fatal(err)
    }
    varmap := map[string]interface{}{
        "var1": "value",
        "var2": 100,
    }
    tmpl.ExecuteTemplate(os.Stdout, "index", varmap)

}
like image 157
fabrizioM Avatar answered Oct 23 '22 12:10

fabrizioM