Skip to content

Add template tag to enable derived values for string fields - #83

Merged
bxcodec merged 6 commits into
go-faker:mainfrom
rizesky:template-tag-support
Aug 14, 2026
Merged

bxcodec merged 6 commits into
go-faker:mainfrom
rizesky:template-tag-support

Conversation

@rizesky

@rizesky rizesky commented Oct 15, 2025

Copy link
Copy Markdown
Contributor

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
}

Comment thread example_template_tag_test.go Resolved
Comment thread template_tag.go Resolved
Comment thread template_tag.go Resolved
@geshtng

geshtng commented Oct 29, 2025 •

Copy link
Copy Markdown
Member

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

image

@rizesky

rizesky commented Oct 29, 2025

Copy link
Copy Markdown
Contributor Author

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

@geshtng

geshtng commented Nov 1, 2025

Copy link
Copy Markdown
Member

@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

Comment thread template_tag.go Resolved
Comment thread example_template_tag_test.go Resolved
@geshtng

geshtng commented Nov 15, 2025

Copy link
Copy Markdown
Member

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

geshtng commented Nov 15, 2025

Copy link
Copy Markdown
Member

You still need to check about these possible bugs:

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

@rizesky

rizesky commented Apr 9, 2026

Copy link
Copy Markdown
Contributor Author

@geshtng Sorry, just have time to look at this PR again.
I have a new commit, that I'm sure already cover are 3 possible bugs you mentioned.
Please review

@geshtng

geshtng commented May 31, 2026

Copy link
Copy Markdown
Member

@rizesky
Minor bug. Need to check if the field is exported or not.
Test file:

func TestTemplateTagWithUnexportedField(t *testing.T) {
	type PrivateField struct {
		password  string // unexported — triggers panic in ctx-building loop
		FirstName string `faker:"first_name"`
		Slug      string `faker:"template:{{.FirstName | slug}}"`
	}

	var u PrivateField

	if err := FakeData(&u); err != nil {
		t.Fatal(err)
	}
	if u.Slug == "" {
		t.Fatal("expected non-empty Slug")
	}
}

Log:
image

rizesky and others added 6 commits August 8, 2026 20:05
…efix matches

- faker.go: only treat tags of the form `template:...` as template fields,
  so bare `template` and unrelated tags like `templated` are no longer hijacked.
- template_tag.go: enable `missingkey=error` so references to undefined fields
  fail loudly instead of expanding to `<no value>`; detect self, forward, and
  circular references between template fields and return a descriptive error.
- template_tag_test.go: add regression cases for circular, self, forward, and
  missing-field references, plus a prefix-parsing test covering both the
  no-colon and false-prefix cases.
Addresses the review feedback on this PR.

Unexported fields: the second pass built a map[string]any by calling
reflect.Value.Interface on every field of the struct, which panics for
unexported ones, so any struct with both an unexported field and a template
field crashed FakeData. Templates now render against the struct itself, so
unexported fields are simply not reachable and referencing one is a clean
error rather than a panic. Rendering the struct also gives nested field
access, promoted fields of embedded structs and non-string values for free.

Field order: a template referencing a template field declared later in the
struct was rejected outright. Template fields are now evaluated in dependency
order, worked out by a topological sort over the references each template
actually makes, so declaration order no longer matters. Only a real cycle is
an error, and the message names its members.

References are extracted by walking the parsed template rather than matching
the source with a regular expression. Only the parse tree can tell a
reference from literal text such as "@Example.Com", report {{.Addr.City}} as
a reference to Addr alone, and see that range and with rebind the dot — the
last of which would otherwise invent dependencies and so report cycles that
do not exist.

Tag parsing: decodeTags splits a tag on commas and matches each chunk against
PriorityTags, which mangled template bodies. `template:...,unique` and
`template:...,keep` both blanked the tag, silently filling the field with a
random string, and a body containing something like ", email: {{.X}}" was
hijacked by the email tag. The body is now captured before the priority
scanner runs, so it may contain commas; keep and unique keep their usual
meaning as standalone chunks.

keep is honoured for template fields: a non-zero incoming value is kept.
unique is rejected, because a template over fixed inputs is deterministic and
the retry loop could never produce a different value.

Also: validate the destination type before evaluating anything, so a bad tag
cannot leave some fields written and others not; support named string types
and *string; keep Unicode letters and digits in slug, which used to return ""
for names from the Chinese and Russian providers; and unexport
EvaluateTemplateFields, which exposed reflect internals as public API.

The suite only exercised EvaluateTemplateFields directly, with hand-built
reflect values, so none of the bugs above could have been caught: they all
surface through FakeData. It now covers the unexported-field repro, dependency
ordering, cycles, comma-containing bodies, keep/unique, non-string and pointer
fields, nested and embedded structs, slice elements, option overrides, custom
tag names, unicode slugs and concurrent use, with unit tables for decodeTags,
reference extraction and the topological sort. TestTemplateTagPrefixParsing
asserted `err == nil && x == "..."`, which passed whenever any error was
returned; it now asserts the exact error.

The example had no Output block, so it compiled but never ran. Its inputs are
now pinned with field providers and it asserts its output, and it declares
Email before Username to demonstrate dependency ordering.
Follows how the other tags are documented here: a link to the example file in
the Example list, and one Limitation bullet in the same shape as the `oneof`
one.
@rizesky
rizesky force-pushed the template-tag-support branch from 6c1fac3 to a27c1e7 Compare August 8, 2026 13:51
@rizesky

rizesky commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

Hi @geshtng just have time to get back to this, fixed, and I add some more comments and tests to make it safer and clearer

@geshtng

geshtng commented Aug 12, 2026

Copy link
Copy Markdown
Member

Wdyt? @bxcodec

@bxcodec bxcodec left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks for the feature @rizesky

@bxcodec
bxcodec merged commit be46373 into go-faker:main Aug 14, 2026
2 checks passed
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.

3 participants