Iliketoproveit
Iliketoproveit

Reputation: 445

Saving HTML to a golang template variables

I am using go-lang templates to output some HTML. There is a block of HTML that I will like to repeat many times. So I am using a variable to store this block of HTML. Here is a dummy version of my code:

package main

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

var tmplString = `    // content of index.html
    {{define "index"}}
    {{ $DUMMY := "{{.var1}} is equal to {{.var2}}"  }}
    {{ $DUMMY }}
    {{ $DUMMY }}
    {{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)

}

The problem is that this piece of code will

{{.var1}} is equal to {{.var2}}
{{.var1}} is equal to {{.var2}}

But I need it to produce

value is equal to 100
value is equal to 100

How can I define a variable so that the string gets built from my structure?

Upvotes: 0

Views: 1243

Answers (1)

sieberts
sieberts

Reputation: 538

You can concatenate strings in templates with print:

 {{ $DUMMY := (print .var1 " is equal to " .var2 )}}

Upvotes: 2

Related Questions