diff --git a/helper.go b/helper.go index a44c8ff..de8b3df 100644 --- a/helper.go +++ b/helper.go @@ -36,6 +36,7 @@ func init() { RegisterHelper("equal", equalHelper) RegisterHelper("ifGt", ifGtHelper) RegisterHelper("ifLt", ifLtHelper) + RegisterHelper("ifEq", ifEqHelper) } // RegisterHelper registers a global helper. That helper will be available to all templates. @@ -346,6 +347,26 @@ func ifLtHelper(a, b interface{}, options *Options) interface{} { return options.Inverse() } +func ifEqHelper(a, b interface{}, options *Options) interface{} { + var aFloat, bFloat float64 + var err error + + if aFloat, err = floatValue(a); err != nil { + // TODO: Log conversion failure. + return options.Inverse() + } + if bFloat, err = floatValue(b); err != nil { + // TODO: Log conversion failure + return options.Inverse() + } + + if aFloat == bFloat { + return options.Fn() + } + // Evaluate possible else condition. + return options.Inverse() +} + // #unless block helper func unlessHelper(conditional interface{}, options *Options) interface{} { if options.isIncludableZero() || IsTrue(conditional) { diff --git a/helper_test.go b/helper_test.go index b5b3089..3b6fa60 100644 --- a/helper_test.go +++ b/helper_test.go @@ -306,6 +306,62 @@ var helperTests = []Test{ nil, nil, nil, `foo or bar are not numbers`, }, + { + "#ifEq helper with true literal", + `{{#ifEq foo 10}}foo is equal to 10{{/ifEq}}`, + map[string]interface{}{"foo": 10}, + nil, nil, nil, + `foo is equal to 10`, + }, + { + "#ifEq helper with false literal", + `{{#ifEq foo 10}}foo is equal to 10{{/ifEq}}`, + map[string]interface{}{"foo": 15}, + nil, nil, nil, + ``, + }, + { + "#ifEq helper with true literal from params", + `{{#ifEq foo bar}}foo is equal to bar{{/ifEq}}`, + map[string]interface{}{"foo": 5, "bar": 5}, + nil, nil, nil, + `foo is equal to bar`, + }, + { + "#ifEq helper with string comparison", + `{{#ifEq foo bar}}foo is equal to bar{{/ifEq}}`, + map[string]interface{}{"foo": "5", "bar": "5"}, + nil, nil, nil, + `foo is equal to bar`, + }, + { + "#ifEq helper with false literal from params", + `{{#ifEq foo bar}}foo is equal to bar{{/ifEq}}`, + map[string]interface{}{"foo": 5, "bar": 5}, + nil, nil, nil, + `foo is equal to bar`, + }, + { + "#ifEq helper with else condition", + `{{#ifEq foo bar}}foo is equal to bar{{else}}foo is not equal to bar{{/ifEq}}`, + map[string]interface{}{"foo": 6, "bar": 5}, + nil, nil, nil, + `foo is not equal to bar`, + }, + { + "#ifEq helper non-numbers", + `{{#ifEq foo bar}}foo is equal to bar{{/ifEq}}`, + map[string]interface{}{"foo": "foo", "bar": "bar"}, + nil, nil, nil, + ``, + }, + { + "#ifEq helper non-numbers with else condition", + `{{#ifEq foo bar}}foo is equal to bar{{else}}foo or bar are not numbers{{/ifEq}}`, + map[string]interface{}{"foo": "foo", "bar": "bar"}, + nil, nil, nil, + `foo or bar are not numbers`, + }, { "#equal helper inside HTML tag", ``,