brianvoe / gofakeit

Random fake data generator written in go
MIT License
4.49k stars 263 forks source link

Generate some data with custom template function #279

Closed maximargo closed 8 months ago

maximargo commented 8 months ago

Hi! When I try to run the following code I get this error: "template: CodeRun:1: function "title" not defined". What I'm missing?

package main

import (
    "fmt"
    "strings"
    "text/template"

    "github.com/brianvoe/gofakeit/v6"
)

func main() {
    f := gofakeit.New(11)
    s := `{{printf "%q" . | title}}`

    funcMap := template.FuncMap{
        "title": strings.Title,
    }

    r, err := f.Template(s, &gofakeit.TemplateOptions{Funcs: funcMap, Data: "the go programming language"})
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(r)
}
brianvoe commented 8 months ago

hmmm interesting. The only thing I can think of is the pipe call.

@Mrpye Any idea on this one?

Mrpye commented 8 months ago

Found two issues

First, the string needs to be

s := `{{printf "%q" . | title}}`

to

s := `{{printf "%q" (title .Data)}}`

customer data is put in the data model and with nested functions, you need to wrap in ( )

The second issue is with the code, the user functions are not getting added to the function map. looks like this got removed at some point so will need adding back in

func templateFuncMap(r *rand.Rand, fm *template.FuncMap) *template.FuncMap {
...

        // Fix merge the user function maps with the template function map
    for k, v := range *fm {
        funcMap[k] = v
    }

    return &funcMap
}
brianvoe commented 8 months ago

Fixed v6.26.4