How can I add a default value to a go text/template?

huangapple go评论83阅读模式
英文:

How can I add a default value to a go text/template?

问题

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

template: t2:2:20: 执行“t2”时出错,位置为<index .table_name 0>:调用index时出错:未定义的nil的索引

以下是代码示例:https://play.golang.org/p/BwlpROrhm6

// text/template是一个有用的文本生成工具。
// 相关示例: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() {
	// 定义模板
	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模板引擎中有一个isset函数,但我无法弄清楚它是如何实现的,而且我也不确定它是否能解决我的问题。

英文:

I want to create a golang template with a default value that is used if a parameter is not supplied, but if I try to use the or function in my template, it gives me this error:

template: t2:2:20: executing &quot;t2&quot; at &lt;index .table_name 0&gt;: error calling index: index of untyped nil

Here's an example of the code: 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 (
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;text/template&quot;
)

var fullParams = map[string][]string{
	&quot;table_name&quot;: []string{&quot;TableNameFromParameters&quot;},
	&quot;min&quot;:        []string{&quot;100&quot;},
	&quot;max&quot;:        []string{&quot;500&quot;},
}
var minimalParams = map[string][]string{
	&quot;min&quot;: []string{&quot;100&quot;},
	&quot;max&quot;: []string{&quot;500&quot;},
}

func check(err error) {
	if err != nil {
		fmt.Print(err)
	}
}

func main() {
	// Define Template
	t := template.Must(template.New(&quot;t2&quot;).Parse(`
		{{$table_name := (index .table_name 0) or &quot;DefaultTableName&quot;}}
		Hello World!
		The table name is {{$table_name}}
	`))
	check(t.Execute(os.Stdout, fullParams))
	check(t.Execute(os.Stdout, minimalParams))
}

Googling has pointed me towards an isset function in hugo's template engine, but I can't figure out how they implemented it, and I am not sure if it would even solve my problem.

答案1

得分: 14

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

{or .value "Default"}

从文档中可以看到:

or
通过返回第一个非空参数或最后一个参数,返回其参数的布尔或运算结果,即“如果x为真则返回x,否则返回y”。所有参数都会被求值。

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

Playground Demo

英文:

You can use the function or in the template. This seems the simplest option.

{or .value &quot;Default&quot;}

From the docs:

or
        Returns the boolean OR of its arguments by returning the
        first non-empty argument or the last argument, that is,
        &quot;or x y&quot; behaves as &quot;if x then x else y&quot;. All the
        arguments are evaluated.

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

Playground Demo

答案2

得分: 7

另一种解决方案是通过更改模板定义来实现:

// 定义模板
t := template.Must(template.New("t2").Parse(`
	Hello World!
	The table name is {{with .table_name}}{{index . 0}}{{else}}DefaultTableName{{end}}
`))

但是,该值不会存储在变量中,因此如果您想在其他地方重用它,您需要再次编写它。标准模板包的主要目的是用于渲染预先计算的值,而与逻辑相关的操作/函数的能力有限。但是,您可以定义自己的函数,然后将其注册到模板的FuncMap中,例如由@jeevatkm提到的default函数。

英文:

Another solution is by changing the template definition to

// Define Template
t := template.Must(template.New(&quot;t2&quot;).Parse(`
	Hello World!
	The table name is {{with .table_name}}{{index . 0}}{{else}}DefaultTableName{{end}}
`))

But, the value won't be stored in a variable, so if you want to reuse it in other places, you need to write it again. The main purpose of the standard template package is for rendering precomputed value, and logic related operations/functions have limited capability. However, you can define your own function then register it to the template's FuncMap e.g. the default function mentioned by @jeevatkm.

答案3

得分: 2

Go模板没有default函数。但是你可以使用提供default函数的库。

例如:github.com/leekchan/gtf

在这里查看它在https://github.com/leekchan/gtf/blob/master/gtf.go#L28中的实现。


在这里阅读hugo的isset函数这里,源代码在这里

英文:

Go template does not have default function. However you can use library that provides default func.

For e.g.: github.com/leekchan/gtf

Refer here, how it is implemented at https://github.com/leekchan/gtf/blob/master/gtf.go#L28


Read hugo isset func here and source is here

huangapple
  • 本文由 发表于 2017年6月14日 05:39:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/44532017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定