2017-06-13 81 views
2

我想创建一个如果不提供的参数使用默认值的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)) 
} 

谷歌搜索指出我朝着isset功能hugo's template engine,但我想不出他们是如何实现它,我不知道如果它甚至会解决我的问题。

回答

3

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

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

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

+1

这当然不是漂亮,但它的作品!我认为你的预期目标是正确的 - 我应该在模板之外提交默认值。我会记住这个项目的未来版本。 – Noah

相关问题