go - Gomplate : bad character U+0022 '-'

标签 go yaml gomplate

我正在尝试gomplate并遇到错误。
对于上下文,我已经定义了一个模板文件test.tmplt和一个数据源文件dev.yaml。
test.tmplt具有以下内容:

localAPIEndpoint:
    advertiseAddress: {{ (datasource "k8s").api-advertise-ip }}
而dev.yaml包含以下内容:
api-advertise-ip: 192.168.0.1
如果我尝试像这样使用gomplate填写test.tmplt的内容:
gomplate -d k8s=./dev.yaml -f ./test.tmplt -o test.conf
我收到以下错误:
09:42:44 FTL  error="template: ./test.tmplt:2: bad character U+002D '-'"
在我看来,它不喜欢模板文件中的“-”符号。有任何解决方法吗?这是预期的行为吗?
编辑1:
感谢@icza提供的答案对于上面的示例正确运行。但是,如果我将yaml文件修改为具有嵌套字段,它似乎会崩溃。
例如
dev.yaml:
kubernetes:
    api-advertise-ip: 192.168.0.0
test.tmplt:
localAPIEndpoint:
    advertiseAddress: {{ index (datasource "k8s") "kubernetes.api-advertise-ip" }}
在这种情况下,输出:
gomplate -d k8s=./dev.yaml -f ./test.tmplt -o test.conf
是 :
localAPIEndpoint:
    advertiseAddress: <no value>

最佳答案

您的"k8s"数据源是一个YAML配置,您想访问它的api-advertise-ip属性。
由于api-advertise-ip包含破折号,因此您不能在模板中按原样使用名称,因为这是一种语法错误:模板引擎尝试使用api作为属性名称,其后的破折号是语法错误。
您必须将属性名称放在包含破折号的引号中:"api-advertise-ip",但这使用.选择器也是无效的语法。
使用内置的index函数使用以下 key 为YAML数据源建立索引:

localAPIEndpoint:
    advertiseAddress: {{ index (datasource "k8s") "api-advertise-ip" }}
gomplate在后台使用 text/template ,请参阅Go Playground上的工作示例。
当使用index且您具有多个嵌套级别时,请将每个键作为index的附加参数提供。
例如:
localAPIEndpoint:
    advertiseAddress: {{ index (datasource "k8s") "kubernetes" "api-advertise-ip" }}
Go Playground上尝试这个。

关于go - Gomplate : bad character U+0022 '-' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64908171/

相关文章:

image - Golang Iris Web - 提供 1x1 像素

linux - 将数组从 .env 传递到 docker-compose.yml 到 Dockerfile 到 bash 脚本

yaml - 如何在同一任务中展开多个列表

Azure Devops 管道 - Yaml Powershell 脚本路径

go - 如何为多个环境和突变的组合生成配置

testing - 在 go test 中处理命令行参数

go - Echo 无法在 HTTPErrorHandler 中使用自定义上下文

json - 请求正文日期解析问题