Reputation: 516
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 "t2" at <index .table_name 0>: 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 (
"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 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.
Upvotes: 8
Views: 30896
Reputation: 8091
You can use the function or
in the template. This seems the simplest option.
{or .value "Default"}
From the docs:
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
Upvotes: 26
Reputation: 6444
Another solution is by changing the template definition to
// Define Template
t := template.Must(template.New("t2").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.
Upvotes: 7
Reputation: 4781
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
Upvotes: 2