Error - Pass struct to text/template

Hello,
I have a problem.
I try to pass a struct to a template, but the values go null

Example:

    package main

        import (
        	"fmt"
        	"log"
        	"os"
        	"text/template"
        )

        var tpl *template.Template

        type values struct {
        	stringPagar   string
        	stringReceber string
        }

        func init() {
        	tpl = template.Must(template.ParseFiles("tpl.gohtml"))
        }

        func main() {

        	err := os.Remove("test.txt") //delet
        	if err != nil {
        		log.Fatal(err)
        	}

        	nf, err := os.Create("test.txt")
        	if err != nil { 
        		log.Fatal(err)
        	}
        	defer nf.Close()

        	fmt.Println("Hello")

        	valores := values{
        		stringPagar:   "100,200,300",
        		stringReceber: "400,500,600",
        	}

        	tpl.ExecuteTemplate(nf, "tpl.gohtml", valores)
        }

My tpl.gohtml:

Test
{{.stringPagar}}

Test 2 
{{.stringReceber}}

Result in test.txt

Test

Can someone help me?

1 Like

values.stringPagar and values.stringReceber need to be exported (i.e., begin with capital letters) to be accessed from within the template.

2 Likes
  1. A version that runs on the playground: https://play.golang.org/p/ICFypEzj0B0
  2. A version that checks for err after/when executing the template: https://play.golang.org/p/h-rOFtCXjkU

The second version prints enough information on your terminal to find the solution.

If not, please ask what the output actually means, but either way, please make it a habbit to check for returned errors.

3 Likes

It worked. Very thanks

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.