Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for numeric map keys #269

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions pongo2_issues_test.go
Expand Up @@ -27,3 +27,24 @@ func TestIssue151(t *testing.T) {
t.Fatalf("Expected output 'foobarbaz', but got '%s'.", str)
}
}

func TestNumericMapKey(t *testing.T) {
tpl, err := pongo2.FromString("{{ mydict.0 }}{{ mydict.2 }}")
if err != nil {
t.Fatal(err)
}

str, err := tpl.Execute(pongo2.Context{
"mydict": map[string]interface{}{
"0": "foo",
"1": "bar",
},
})
if err != nil {
t.Fatal(err)
}

if str != "foo" {
t.Fatalf("Expected output 'foo', but got '%s'.", str)
}
}
4 changes: 3 additions & 1 deletion variable.go
Expand Up @@ -269,7 +269,7 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
switch part.typ {
case varTypeInt:
// Calling an index is only possible for:
// * slices/arrays/strings
// * slices/arrays/strings/maps
switch current.Kind() {
case reflect.String, reflect.Array, reflect.Slice:
if part.i >= 0 && current.Len() > part.i {
Expand All @@ -278,6 +278,8 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
// In Django, exceeding the length of a list is just empty.
return AsValue(nil), nil
}
case reflect.Map:
current = current.MapIndex(reflect.ValueOf(strconv.Itoa(part.i)))
default:
return nil, fmt.Errorf("Can't access an index on type %s (variable %s)",
current.Kind().String(), vr.String())
Expand Down