diff options
author | Bjørn Erik Pedersen <[email protected]> | 2017-08-17 10:24:17 +0200 |
---|---|---|
committer | Bjørn Erik Pedersen <[email protected]> | 2017-08-18 07:36:32 +0200 |
commit | 08f48b91d68d3002b887ddf737456ff0cc4e786d (patch) | |
tree | d0f37154d11cc6f5ab8d543d025e708cdc9f4acc /tpl/compare | |
parent | 2fc121ce2308b090ab67cbeb3039c53f5eedaa64 (diff) | |
download | hugo-08f48b91d68d3002b887ddf737456ff0cc4e786d.tar.gz hugo-08f48b91d68d3002b887ddf737456ff0cc4e786d.zip |
compare, hugolib, tpl: Add Eqer interface
And use it in `eq` and `ne` so `Page` values can be compared directly in the templates without thinking about it being a `Page` or a `PageOutput` wrapper.
Fixes #3807
Diffstat (limited to 'tpl/compare')
-rw-r--r-- | tpl/compare/compare.go | 10 | ||||
-rw-r--r-- | tpl/compare/compare_test.go | 23 |
2 files changed, 33 insertions, 0 deletions
diff --git a/tpl/compare/compare.go b/tpl/compare/compare.go index 1482c0afe..2df03b7db 100644 --- a/tpl/compare/compare.go +++ b/tpl/compare/compare.go @@ -18,6 +18,8 @@ import ( "reflect" "strconv" "time" + + "github.com/gohugoio/hugo/compare" ) // New returns a new instance of the compare-namespaced template functions. @@ -85,6 +87,14 @@ func (*Namespace) Default(dflt interface{}, given ...interface{}) (interface{}, // Eq returns the boolean truth of arg1 == arg2. func (*Namespace) Eq(x, y interface{}) bool { + + // hugolib.Page implements compare.Eqer to make Page and PageOutput comparable. + if e1, ok := x.(compare.Eqer); ok { + if e2, ok := y.(compare.Eqer); ok { + return e1.Eq(e2) + } + } + normalize := func(v interface{}) interface{} { vv := reflect.ValueOf(v) switch vv.Kind() { diff --git a/tpl/compare/compare_test.go b/tpl/compare/compare_test.go index 57f061f4d..9adbcf574 100644 --- a/tpl/compare/compare_test.go +++ b/tpl/compare/compare_test.go @@ -26,6 +26,25 @@ import ( "github.com/stretchr/testify/require" ) +type tstEqerType1 string +type tstEqerType2 string + +func (t tstEqerType2) Eq(other interface{}) bool { + return cast.ToString(t) == cast.ToString(other) +} + +func (t tstEqerType2) String() string { + return string(t) +} + +func (t tstEqerType1) Eq(other interface{}) bool { + return cast.ToString(t) == cast.ToString(other) +} + +func (t tstEqerType1) String() string { + return string(t) +} + type tstCompareType int const ( @@ -148,6 +167,10 @@ func doTestCompare(t *testing.T, tp tstCompareType, funcUnderTest func(a, b inte {"a", "a", 0}, {"a", "b", -1}, {"b", "a", 1}, + {tstEqerType1("a"), tstEqerType1("a"), 0}, + {tstEqerType1("a"), tstEqerType2("a"), 0}, + {tstEqerType2("a"), tstEqerType1("a"), 0}, + {tstEqerType2("a"), tstEqerType1("b"), -1}, } { result := funcUnderTest(test.left, test.right) success := false |