-2

I am building a CLI to generate code for an homemade API framework (right now to generate the controller part). To do so, I am using template, but I saw that the template is generating nothing (an empty file), when I use words such as package or func in the template.

I want to build the following template:

package controllers

{{- range .Methods }}
    {{ if eq .Name "Create" }}
            func ({{ firstChar $.ModelName }}c {{ title $.ModelName }}Controller) Get{{ title $.ModelName }}(c *gin.Context) {
                {{ $.ModelName }}, err := store.Find{{ title $.ModelName }}ById(c, c.Param("id"))

                if err != nil {
                    c.AbortWithError(http.StatusNotFound, helpers.ErrorWithCode("{{ $.ModelName }}_not_found", "The {{ $.ModelName }} does not exist", err))
                    return
                }

                c.JSON(http.StatusOK, {{ $.ModelName }})
            }
    {{ else if eq .Name "Get" }}
    {{ else if eq .Name "GetAll" }}
    {{ else if eq .Name "Update" }}
    {{ else if eq .Name "Delete" }}
    {{ end }}
{{- end }}

Do you have any idea of how to make template working?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Adrien Chapelet
  • 386
  • 4
  • 24
  • 6
    You need to create a [mcve] demonstrating the issue. The template package doesn't care what the rest of the text is: https://play.golang.org/p/vbm0qTbAdlL – JimB Mar 14 '19 at 22:48
  • 1
    What JimB said; also adding `Option("missingkey=error")` in the code might reveal an error (if any). – Martin Tournoij Mar 15 '19 at 06:09

1 Answers1

0

It's now working, I just add template.Must before template.New and it's now working like a charm.

path := filepath.Join("templates", "controller.tmpl")
    body, _ := ioutil.ReadFile(path)
    tmpl := template.Must(template.New("model").Funcs(funcMap).Parse(string(body)))

    var buf bytes.Buffer
    err := tmpl.Execute(&buf, selectedMethods)
    utils.Check(err)

    src, _ := format.Source(buf.Bytes())
Adrien Chapelet
  • 386
  • 4
  • 24
  • `template.Must ` does not change how templates are handled. If it changes your program _at all_, it's going to panic because you weren't properly handling an error. – JimB Mar 15 '19 at 14:20