Skip to content

Commit

Permalink
Merge pull request #295 from zoncoen/template
Browse files Browse the repository at this point in the history
fix(template): evaluate only an expression that matched the condition
  • Loading branch information
zoncoen committed Apr 12, 2023
2 parents de0d93a + bff5e98 commit 17286b1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
12 changes: 2 additions & 10 deletions template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -437,18 +437,10 @@ func (t *Template) executeConditionalExpr(e *ast.ConditionalExpr, data interface
if !ok {
return nil, fmt.Errorf("invalid operation: operator ? not defined on %#v (value of type %T)", c, c)
}
x, err := t.executeExpr(e.X, data)
if err != nil {
return nil, err
}
y, err := t.executeExpr(e.Y, data)
if err != nil {
return nil, err
}
if condition {
return x, nil
return t.executeExpr(e.X, data)
}
return y, nil
return t.executeExpr(e.Y, data)
}

// align indents of marshaled texts
Expand Down
15 changes: 12 additions & 3 deletions template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1036,9 +1036,18 @@ func TestTemplate_Execute_BinaryExpr(t *testing.T) {
str: `{{1 ? 1 : 2}}`,
expectError: `failed to execute: {{1 ? 1 : 2}}: invalid operation: operator ? not defined on 1 (value of type int64)`,
},
"true ? 1 : 2 + true": {
str: `{{true ? 1 : 2 + true}}`,
expectError: `failed to execute: {{true ? 1 : 2 + true}}: invalid operation: 2 + true: mismatched types int64 and bool`,
`defined(v) ? v : "default" + true`: {
// "default" + true should not be evaluated
str: `{{defined(v) ? v : "default" + true}}`,
data: map[string]interface{}{
"v": "override",
},
expect: "override",
},
`defined(v) ? v + true : "default"`: {
// v + true should not be evaluated
str: `{{defined(v) ? v : "default"}}`,
expect: "default",
},
}
runExecute(t, tests)
Expand Down

0 comments on commit 17286b1

Please sign in to comment.