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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题