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

标签 templates go

我想创建一个带有默认值的 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/

相关文章:

go - 意外的模块路径 "github.com/sirupsen/logrus"

templates - Go:在模板文件中打印 URI(echo 框架)

c++ - 在编译时或运行时将 const char * 映射到 duck-typed T

c++ - 模板元编程 : checking for existence of a function defined later

json - 如何将带有小写成员的简单json解码为结构

go - 在从 Golang Buffalo 网络应用程序发送推文时设置 CSRF token 时遇到问题

c++ - AVL 树 C++ 的 Ostream 运算符

c++ - 使用 const char * 时如何将记录器与模板一起使用?

go - 使用表单数据和身份验证在 Go 中发出 POST 请求

testing - Golang 测试模拟函数最佳实践