![](/img/trans.png)
[英]Go text/template templates: how to check value against an array of values within the template itself?
[英]How can I add a default value to a go text/template?
我想使用默认值创建一个golang模板,如果未提供参数,则使用该默认值,但是如果我尝试在模板中使用or
函数,则会出现此错误:
template: t2:2:20: executing "t2" at <index .table_name 0>: error calling index: index of untyped nil
这是代码示例: 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))
}
Googling向我指出了hugo模板引擎中的isset
函数,但我无法弄清楚它们是如何实现的,而且我不确定它是否还能解决我的问题。
另一种解决方案是将模板定义更改为
// Define Template
t := template.Must(template.New("t2").Parse(`
Hello World!
The table name is {{with .table_name}}{{index . 0}}{{else}}DefaultTableName{{end}}
`))
但是,该值不会存储在变量中,因此,如果要在其他地方重用它,则需要重新编写它。 标准模板包的主要目的是呈现预先计算的值,并且与逻辑相关的操作/功能的功能有限。 但是,您可以定义自己的function
然后将其注册到模板的FuncMap中,例如@jeevatkm提到的default
函数。
Go模板不具有default
功能。 但是,您可以使用提供default
功能的库。
例如: github.com/leekchan/gtf
请参阅此处,如何在https://github.com/leekchan/gtf/blob/master/gtf.go#L28上实现它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.