dtyqflrr775518 2018-04-20 03:49 采纳率: 100%
浏览 236

防止golang文本/模板库插入“ <no value>”

Go places <no value> as the result of a the template expansion when no value is present for a particular template parameter.

Is there any way to prevent this? All I can think of right now is to insert an empty version of "AppVersion" into the data map

e.g.

package main

import (
    "text/template"
    "log"
    "bytes"
    "fmt"
)

func main() {
    data := make(map[string]string)
    //data["AppVersion"] = "Octane_3.0"

    text := "APP_VERSION={{.AppVersion}}"
    tmpl, err := template.New("").Parse(text)
    if err != nil {
        log.Fatal(err)
    }

    var b bytes.Buffer
    err = tmpl.Execute(&b, data)
    if err != nil {
        fmt.Println("template.Execute failed", err)
    }

    fmt.Println("Template text:", text)
    fmt.Println("Expanded:", b.String())
}

https://play.golang.org/p/OuLhcHOCsWJ

  • 写回答

1条回答 默认 最新

  • dongmeng4742 2018-04-20 03:53
    关注

    Ooops, found the answer if anyone interested I'll leave the question & answer up.

    tmpl, err := template.New("").Option("missingkey=zero").Parse(text)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀