Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions pongo2_issues_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,53 @@ func TestIssue297(t *testing.T) {
t.Fatalf("Expected `Testing: one two three four\nfive six!`, but got `%v`.", str)
}
}

type StructWithoutTag struct {
Name string
Age int
}

type StructWithTag struct {
Name string `pongo2:"my_name"`
Age int `pongo2:"my_age"`
}

func TestIssue319StrutWithTag(t *testing.T) {
s := StructWithTag{
Name: "Andy Dufresne",
Age: 23,
}
ctx := pongo2.Context{
"mystruct": s,
}
template := `My name is {{ mystruct.my_name }}, age is {{ mystruct.my_age }}`
out, err := pongo2.FromString(template)
if err != nil {
t.Error(err)
}
execute, err := out.Execute(ctx)
if err != nil {
t.Error(err)
}
mustEqual(t, execute, "My name is Andy Dufresne, age is 23")
}

func TestIssue319StrutWithoutTag(t *testing.T) {
s := StructWithoutTag{
Name: "Andy Dufresne",
Age: 23,
}
ctx := pongo2.Context{
"mystruct": s,
}
template := `My name is {{ mystruct.Name }}, age is {{ mystruct.Age }}`
out, err := pongo2.FromString(template)
if err != nil {
t.Error(err)
}
execute, err := out.Execute(ctx)
if err != nil {
t.Error(err)
}
mustEqual(t, execute, "My name is Andy Dufresne, age is 23")
}
19 changes: 18 additions & 1 deletion variable.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,24 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
// Calling a field or key
switch current.Kind() {
case reflect.Struct:
current = current.FieldByName(part.s)
//save tag and field name into map
tagMap := make(map[string]string)
//get all tags of current struct
fields := current.NumField()
for i := 0; i < fields; i++ {
field := current.Type().Field(i)
tagMap[field.Tag.Get("pongo2")] = field.Name
}
//get all tags of current field
field := current.FieldByName(part.s)
if !field.IsValid() {
//if field is not valid, try to get field by tag
if tagMap[part.s] != "" {
current = current.FieldByName(tagMap[part.s])
}
} else {
current = field
}
case reflect.Map:
current = current.MapIndex(reflect.ValueOf(part.s))
default:
Expand Down