From c13c01eb96a7325e5a521f2fc64c63ef0a170071 Mon Sep 17 00:00:00 2001 From: Takumi2008 Date: Tue, 10 Aug 2021 11:48:26 -0500 Subject: [PATCH] add ifGt helper --- helper.go | 18 ++++++++++++++++++ helper_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/helper.go b/helper.go index 3a5236e..50265db 100644 --- a/helper.go +++ b/helper.go @@ -32,6 +32,7 @@ func init() { RegisterHelper("log", logHelper) RegisterHelper("lookup", lookupHelper) RegisterHelper("equal", equalHelper) + RegisterHelper("ifGt", ifGtHelper) } // RegisterHelper registers a global helper. That helper will be available to all templates. @@ -302,6 +303,23 @@ func ifHelper(conditional interface{}, options *Options) interface{} { return options.Inverse() } +func ifGtHelper(a, b interface{}, options *Options) interface{} { + // Non-integer comparisons are not supported by the ifGt helper. Return empty string. + var aInt, bInt int + var ok bool + if aInt, ok = a.(int); !ok { + return "" + } + if bInt, ok = b.(int); !ok { + return "" + } + if aInt > bInt { + 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 44d8775..2be1bd4 100644 --- a/helper_test.go +++ b/helper_test.go @@ -194,6 +194,48 @@ var helperTests = []Test{ nil, nil, nil, ``, }, + { + "#ifGt helper with true literal", + `{{#ifGt foo 10}}foo is greater than 10{{/ifGt}}`, + map[string]interface{}{"foo": 11}, + nil, nil, nil, + `foo is greater than 10`, + }, + { + "#ifGt helper with false literal", + `{{#ifGt foo 10}}foo is greater than 10{{/ifGt}}`, + map[string]interface{}{"foo": 5}, + nil, nil, nil, + ``, + }, + { + "#ifGt helper with true literal from params", + `{{#ifGt foo bar}}foo is greater than 10{{/ifGt}}`, + map[string]interface{}{"foo": 5, "bar": 0}, + nil, nil, nil, + `foo is greater than 10`, + }, + { + "#ifGt helper with string comparison, is improper imput should return empty string", + `{{#ifGt foo bar}}foo is greater than 10{{/ifGt}}`, + map[string]interface{}{"foo": "5", "bar": "0"}, + nil, nil, nil, + ``, + }, + { + "#ifGt helper with false literal from params", + `{{#ifGt foo bar}}foo is greater than bar{{/ifGt}}`, + map[string]interface{}{"foo": 5, "bar": 0}, + nil, nil, nil, + `foo is greater than bar`, + }, + { + "#ifGt helper with else condition", + `{{#ifGt foo bar}}foo is greater than bar{{else}}foo is not greater than bar{{/ifGt}}`, + map[string]interface{}{"foo": 0, "bar": 5}, + nil, nil, nil, + `foo is not greater than bar`, + }, { "#equal helper inside HTML tag", ``,