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
37 changes: 37 additions & 0 deletions parser_expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package pongo2
import (
"fmt"
"math"
"strconv"
"strings"
)

type Expression struct {
Expand Down Expand Up @@ -30,6 +32,27 @@ type simpleExpression struct {
opToken *Token
}

func numericStringValue(v *Value) (float64, bool, bool) {
if !v.IsString() {
return 0, false, false
}

s := strings.TrimSpace(v.String())
if s == "" {
return 0, false, false
}

if i, err := strconv.ParseInt(s, 10, 64); err == nil {
return float64(i), false, true
}

if f, err := strconv.ParseFloat(s, 64); err == nil {
return f, true, true
}

return 0, false, false
}

type term struct {
// TODO: Add location token?
factor1 IEvaluator
Expand Down Expand Up @@ -251,6 +274,20 @@ func (expr *simpleExpression) Evaluate(ctx *ExecutionContext) (*Value, error) {
}
switch expr.opToken.Val {
case "+":
if (result.IsString() && t2.IsNumber()) || (t2.IsString() && result.IsNumber()) {
if leftNum, leftIsFloat, ok := numericStringValue(result); ok {
if leftIsFloat || t2.IsFloat() {
return AsValue(leftNum + t2.Float()), nil
}
return AsValue(int(leftNum) + t2.Integer()), nil
}
if rightNum, rightIsFloat, ok := numericStringValue(t2); ok {
if rightIsFloat || result.IsFloat() {
return AsValue(result.Float() + rightNum), nil
}
return AsValue(result.Integer() + int(rightNum)), nil
}
}
if result.IsString() || t2.IsString() {
// Result will be a string
return AsValue(result.String() + t2.String()), nil
Expand Down
18 changes: 18 additions & 0 deletions tags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,24 @@
context: Context{},
expected: "20",
},
{
name: "numeric string plus integer (left)",
template: "{{ a + b }}",

Check failure on line 723 in tags_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of duplicating this literal "{{ a + b }}" 3 times.

See more on https://sonarcloud.io/project/issues?id=flosch_pongo2&issues=AZzH8CiMkolwbU_saNM1&open=AZzH8CiMkolwbU_saNM1&pullRequest=371
context: Context{"a": "10", "b": 5},
expected: "15",
},
{
name: "numeric string plus integer (right)",
template: "{{ a + b }}",
context: Context{"a": 5, "b": "10"},
expected: "15",
},
{
name: "non-numeric string still concatenates",
template: "{{ a + b }}",
context: Context{"a": "x", "b": 5},
expected: "x5",
},
}

for _, tt := range tests {
Expand Down