Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

templates

go

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.

like image 292
Noah Avatar asked Dec 07 '22 18:12

Noah


1 Answers

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

Playground Demo

like image 72
robstarbuck Avatar answered Dec 19 '22 18:12

robstarbuck