Skip to content

Conversation

@rizesky
Copy link

@rizesky rizesky commented Oct 15, 2025

Add template: struct tag which renders a Go text/template using values generated for other fields. Templates are evaluated in a second pass after non-template fields are generated, so templates can reference provider-generated values and other template fields (chaining supported). Small helper functions are also provided.

Rules

  • Only for string type fields

Why
Derived fields (username, email, slug, etc.) are quite common.

Example

type UserProfile struct {
    FirstName string `faker:"first_name"`
    LastName  string `faker:"last_name"`
    Domain    string `faker:"domain_name"`

    // templates using helpers
    Username string `faker:"template:{{.FirstName | lower}}.{{.LastName | lower}}"`
    Slug     string `faker:"template:{{.FirstName | slug}}-{{.LastName | slug}}"`
    Email    string `faker:"template:{{.Username}}@{{.Domain}}"`
}

func main() {
    var u UserProfile
    if err := faker.FakeData(&u); err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", u)
}

//Result
UserProfile{
  FirstName: "John",
  LastName: "Doe",
  Domain: "example.org",
  Username: "john.doe", // lower helper applied
  Slug: "john-doe", // slug helper applied (lower + dashes)
  Email: "[email protected]"// username + domain via template
}

@geshtng
Copy link
Member

geshtng commented Oct 29, 2025

Seems chained feature still failed.
This is the result from my local using your test code (example_template_tag_test.go):

image

@rizesky
Copy link
Author

rizesky commented Oct 29, 2025

@geshtng Can you share how you run the example? I seem to cannot reproduce it.

@geshtng
Copy link
Member

geshtng commented Nov 1, 2025

@geshtng Can you share how you run the example? I seem to cannot reproduce it.

I'm using your code example_template_tag_test.go.
How to reproduce:

  1. Create a new directory inside your project.
  2. Copy your example code, change function Example_templateTag as the main function.
  3. go run main.go
image

@geshtng
Copy link
Member

geshtng commented Nov 15, 2025

Seems it's still has bug to field order.
If a template field depends on another template field that appears later in the struct, it evaluates with the dependency still empty.
This is the result using your example (just put email above the username).
image

@geshtng
Copy link
Member

geshtng commented Nov 15, 2025

You still need to check about these possible bugs:

  1. Circular dependency
  2. Missing field reference
  3. Template tag prefix parsing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants