【问题标题】:How can I add a default value to a go text/template?如何向 go 文本/模板添加默认值?
【发布时间】:2017-06-13 21:39:36
【问题描述】:

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

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 函数,但我无法弄清楚他们是如何实现它的,我不确定它是否能解决我的问题。

【问题讨论】:

    标签: templates go


    【解决方案1】:

    另一种解决方案是将模板定义更改为

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

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

    【讨论】:

    • 它当然不漂亮,但它确实有效!我认为您对预期目的是正确的-我可能应该在模板之外处理默认值。我会牢记这一点,以便将来对该项目进行修订。
    【解决方案2】:

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

    {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

    【讨论】:

    • 当然.value 总是存在的,对吧?
    • 要使其与缺少的键一起工作(至少在docker 下):{{or (index . "Key") "Default"}}
    • 我已经包含了一个演示,希望对您有所帮助。 docker 环境应该不会影响模板的功能。
    • this one 怎么样。而'map has no entry for key "Slot"'正是给我Docker的原因。
    • 对,我想明白你的意思,是的,如果你访问的是映射中的一个键而不是结构中的一个键,你将需要你提到的语法:play.golang.org/p/loWbi4mbpL4 这里提到的更多:stackoverflow.com/questions/26152088/… 不过这应该与 Docker 无关。
    【解决方案3】:

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

    例如:github.com/leekchan/gtf

    参考这里,它是如何在https://github.com/leekchan/gtf/blob/master/gtf.go#L28实现的


    阅读 hugo isset func here 和来源是here

    【讨论】:

      猜你喜欢
      • 2011-10-03
      • 2010-09-21
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      • 2022-08-13
      • 1970-01-01
      相关资源
      最近更新 更多