Golang HTML Template Package Issue

I have these code snippets that parse the HTML files in my template folder:

func ParseTemplateDir(dir string) (*template.Template, error) {
	var paths []string
	err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			paths = append(paths, path)
		}
		return nil
	})

	fmt.Println("Am parsing templates...")

	if err != nil {
		return nil, err
	}

	return template.ParseFiles(paths...)
}

And this is how am accessing the particular HTML template I want to send to the user.

var body bytes.Buffer

	template, err := ParseTemplateDir("templates")
	if err != nil {
		log.Fatal("Could not parse template", err)
	}

	// where templateName can be verificationCode.html or resetPassword.html
	template = template.Lookup(templateName)
	template.Execute(&body, &data)

golang templates

Now when I dynamically access any of the templates, I keep on getting the verificationCode.html template.
When I use resetPassword.html as the templateName, I still get the verificationCode.html template which is weird.
Please how do I fix this?

You are overwriting your list of templates with the single template you looked up, when you reassign to template.

So how do I go about it?

Do not reassign to template when looking up, but use a different name for the looked up template or do not assign the looked up template at all but do template.Lookup(templateName).Execute(&body, &data).

I tried your strategy and yet it’s only the content of the first parsed file that is returned.

I also tried this and it’s still the same issue

if err := template.ExecuteTemplate(&body, templateName, &data); err != nil {
		log.Fatal("Could not execute template", err)
	}

I feel the issue is from the ParseFiles function template.ParseFiles(paths...) because the documentation says it returns the first parsed content.

I have to admit, I did not look at the docs, I just assumed, that the ParseFiles would indeed return a template collection.

This seems not to be the case, you need to parse them individually and sort them into a map from filename/identifier to parsed template.

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