我想创建一个带有默认值的 golang 模板,如果未提供参数,则使用该or模板,但是如果我尝试在模板中使用该函数,则会出现以下错误:
template: t2:2:20: executing "t2" at <index .table_name 0>: error calling index: index of untyped nil
Run Code Online (Sandbox Code Playgroud)
以下是代码示例:https : //play.golang.org/p/BwlpROrhm6
// text/template is a useful text generating tool.
// Related examples: http://golang.org/pkg/text/template/#pkg-examples
package main
import (
"fmt"
"os"
"text/template"
)
var fullParams = map[string][]string{
"table_name": []string{"TableNameFromParameters"},
"min": []string{"100"},
"max": []string{"500"},
}
var minimalParams = map[string][]string{
"min": []string{"100"},
"max": []string{"500"},
}
func check(err error) {
if err != nil {
fmt.Print(err)
}
}
func main() {
// Define Template
t := template.Must(template.New("t2").Parse(`
{{$table_name := (index .table_name 0) or "DefaultTableName"}}
Hello World!
The table name is {{$table_name}}
`))
check(t.Execute(os.Stdout, fullParams))
check(t.Execute(os.Stdout, minimalParams))
}
Run Code Online (Sandbox Code Playgroud)
谷歌搜索给我指出isset了Hugo 模板引擎中的一个函数,但我不知道他们是如何实现它的,我不确定它是否能解决我的问题。
rob*_*uck 21
or您可以使用模板中的功能。这似乎是最简单的选择。
{or .value "Default"}
Run Code Online (Sandbox Code Playgroud)
来自文档:
or
Returns the boolean OR of its arguments by returning the
first non-empty argument or the last argument, that is,
"or x y" behaves as "if x then x else y". All the
arguments are evaluated.
Run Code Online (Sandbox Code Playgroud)
https://golang.org/pkg/text/template/#hdr-Functions
另一种解决方案是将模板定义更改为
// Define Template
t := template.Must(template.New("t2").Parse(`
Hello World!
The table name is {{with .table_name}}{{index . 0}}{{else}}DefaultTableName{{end}}
`))
Run Code Online (Sandbox Code Playgroud)
但是,该值不会存储在变量中,因此如果您想在其他地方重用它,则需要重新编写它。标准模板包的主要用途是渲染预计算值,逻辑相关的操作/函数能力有限。但是,您可以定义自己的,function然后将其注册到模板的FuncMap,例如default@jeevatkm 提到的函数。