gpt4 book ai didi

templates - 如何向 go 文本/模板添加默认值?

转载 作者:IT王子 更新时间:2023-10-29 01:26:29 24 4
gpt4 key购买 nike

我想创建一个带有默认值的 golang 模板,如果未提供参数则使用该默认值,但如果我尝试在我的模板中使用 函数,它会给我这个错误:

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))
}

谷歌搜索已将我指向 hugo's template engine 中的 isset 函数,但我不知道他们是如何实现的,我不确定它是否能解决我的问题。

最佳答案

您可以在模板中使用函数。这似乎是最简单的选择。

{or .value "Default"}

来自文档:

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.

https://golang.org/pkg/text/template/#hdr-Functions

Playground Demo

关于templates - 如何向 go 文本/模板添加默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44532017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com