diff --git a/variable-encoder.go b/variable-encoder.go index 25f083e..cc5c287 100644 --- a/variable-encoder.go +++ b/variable-encoder.go @@ -242,11 +242,19 @@ func (e *VariableEncoder) encodeStruct(v reflect.Value, t reflect.Type) error { for i := 0; i < t.NumField(); i++ { ft, fv := t.Field(i), v.Field(i) if ft.PkgPath == "" { // Ignore unexported fields. + fieldName := ft.Name + if name, ok := ft.Tag.Lookup("typst"); ok { + // Omit fields that have their name set to "-". + if name == "-" { + continue + } + fieldName = name + } + if err := e.writeIndentationCharacters(); err != nil { return err } - // TODO: Allow name customization via struct tags - if err := e.writeStringLiteral([]byte(ft.Name)); err != nil { + if err := e.writeStringLiteral([]byte(fieldName)); err != nil { return err } if err := e.writeString(": "); err != nil { diff --git a/variable-encoder_test.go b/variable-encoder_test.go index 9165a83..f67ce80 100644 --- a/variable-encoder_test.go +++ b/variable-encoder_test.go @@ -126,6 +126,14 @@ func TestVariableEncoder(t *testing.T) { Foo string Bar int }{"Hey!", 12345}, false, "(\n \"Foo\": \"Hey!\",\n \"Bar\": 12345,\n)"}, + {"struct with tags", struct { + Foo string `typst:"foo"` + Bar int `typst:"😀"` + }{"Hey!", 12345}, false, "(\n \"foo\": \"Hey!\",\n \"😀\": 12345,\n)"}, + {"struct with tags omitting", struct { + Foo string `typst:"foo"` + Bar int `typst:"-"` + }{"Hey!", 12345}, false, "(\n \"foo\": \"Hey!\",\n)"}, {"struct empty", struct{}{}, false, "()"}, {"struct empty pointer", (*struct{})(nil), false, "none"}, {"map string string", map[string]string{"Foo": "Bar", "Foo2": "Electric Foogaloo"}, false, "(\n \"Foo\": \"Bar\",\n \"Foo2\": \"Electric Foogaloo\",\n)"},