douxie2023 2017-06-13 21:39
浏览 408
已采纳

如何为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.

  • 写回答

2条回答 默认 最新

  • dpi74187 2017-06-14 00:52
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改