我正在尝试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/