Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "or" with pipelines in go templates?

Tags:

templates

go

How can I use the "or" operator with multiple comparison arguments or any idea where I can find some examples? There seem to be none on the official doc.

if (x == "value" && y == "other") || (x != "a") && (y == "b"){
  print("hello")
}
like image 536
The user with no hat Avatar asked Oct 25 '25 03:10

The user with no hat


1 Answers

The official docs do have explanations for for or, and, eq, and neq for use in templates. You can read about template functions here.

The thing to remember is that the functions provided in templates are prefix notation (Polish Notation). For example the not equal operator ne 1 2 would evaluate to true given that its two arguments 1 and 2 are not equal. Here is an example of a template that uses your given expression rewritten in prefix with template functions.

package main

import (
    "os"
    "text/template"
)

type Values struct {
    Title, X, Y string
}

func main() {
        // Parenthesis are used to illustrate order of operation but could be omitted
    const given_template = `
    {{ if or (and (eq .X "value") (eq .Y "other")) (and (ne .X "a") (eq .Y "b")) }}
    print("hello, {{.Title}}")
    {{end}}`

    values := []Values{
        Values{Title: "first", X: "value", Y: "other"},
        Values{Title: "second", X: "not a", Y: "b"},
        Values{Title: "neither", X: "Hello", Y: "Gopher"},
    }

    t := template.Must(template.New("example").Parse(given_template))

    for _, value := range values {
        err := t.Execute(os.Stdout, &value)

        if err != nil {
            panic(err)
        }
    }
}

Go Playground

like image 69
Ben Campbell Avatar answered Oct 26 '25 19:10

Ben Campbell