emahiro/b.log

Drastically Repeat Yourself !!!!

Goのtemplateにおける値の評価の書き方

Golangのtemplateファイルでisやnot equal、and条件、or条件の書き方を調べたので備忘録です。

※ 適宜追加していきます。

is評価

{{ if eq num 1 }} // if num == 1

// 以下同義
{{ if eq ( .num, 1 ) }}

not equel評価

{{ if ne .num 1 }} // if num != 1

//以下同義
{{ if ne (.num, 1) }}

and 評価

{{ if and (eq .str1 "a") (eq .str2 "b") }} // if str1 == 1 && str2 == b

and A B または and (A, B) になります。

or 評価

{{ if or (eq .str1 "a") (eq .str2 "b") }} // if str1 == 1 || str2 == b

or A B または or (A, B) という書き方になります。

nil 評価

objectのpropertyがnilかどうかを判定したいケースを想定してます。

{{ if .Object.SampleProperty }} 
// SamplePropertyが存在する
{{ else }}
// SamplePropertyがnil
{{ end }}

参考: buildin関数

上記の他にもgoのパッケージである text/tempalte パッケージにはtemplateファイルで使えるbuiltin関数があります。

builtin関数は src/text/template/func.go の中を見ると

type FuncMap map[string]interface{}

var builtins = FuncMap{
    "and":      and,
    "call":     call,
    "html":     HTMLEscaper,
    "index":    index,
    "js":       JSEscaper,
    "len":      length,
    "not":      not,
    "or":       or,
    "print":    fmt.Sprint,
    "printf":   fmt.Sprintf,
    "println":  fmt.Sprintln,
    "urlquery": URLQueryEscaper,

    // Comparisons
    "eq": eq, // ==
    "ge": ge, // >=
    "gt": gt, // >
    "le": le, // <=
    "lt": lt, // <
    "ne": ne, // !=
}

と定義されています。
and関数を確認して見てみると、

// and computes the Boolean AND of its arguments, returning
// the first false argument it encounters, or the last argument.
func and(arg0 reflect.Value, args ...reflect.Value) reflect.Value {
    if !truth(arg0) {
        return arg0
    }
    for i := range args {
        arg0 = args[i]
        if !truth(arg0) {
            break
        }
    }
    return arg0
}

and (A, B, C...) という形式を取るときに、Aから評価していって一つでもfalseがあればfalseを返しています。

templateで使える関数を見るにはこの src/text/template/func.go を参照すれば良いと思います。。