Skip to content

text/template: allow callers to override IsTrue #28391

Open
@bep

Description

@bep

The IsTrue, which is used in templates to determine if if and when etc. conditionals should be invoked makes sense in most situations. Some examples:

package main

import (
	"fmt"
	"text/template"
	"time"
)

func main() {

	type s struct{}

	printIsTrue(1)         // true
	printIsTrue(0)         // false
	printIsTrue(-1)        // true
	printIsTrue(s{})       // true
	printIsTrue(&s{})      // true
	printIsTrue((*s)(nil)) // false
	printIsTrue(nil)       // false
	printIsTrue("")        // false
	printIsTrue("foo")     // true

	printIsTrue(time.Now())  // true
	printIsTrue(time.Time{}) // true

}

func printIsTrue(in interface{}) {
	b, _ := template.IsTrue(in)
	fmt.Println(b)
}

My main challenge with the above is that Struct values are always true-- even the zero time.Time value above.

It would be useful if the above method could check some additional truther interface:

type truther interface {
	IsTrue() bool
}

If the above is considered a breaking change, an alternative suggestion would be to make the template.IsTrue function settable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureRequestIssues asking for a new feature that does not need a proposal.NeedsDecisionFeedback is required from experts, contributors, and/or the community before a change can be made.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions