有没有办法像这样在 yaml 中使用占位符:
foo: &FOO
<<propname>>:
type: number
default: <<default>>
bar:
- *FOO
propname: "some_prop"
default: "some default"
最佳答案
上下文
yaml.load
上用计算值替换占位符问题
示例
考虑以下示例 YAML。它是格式良好的 YAML 语法,但它使用(非标准)花括号占位符和嵌入式表达式。
嵌入的表达式不会在 YAML 中产生所需的结果,因为它们不是 native YAML 规范的一部分。然而,在本示例中使用它们只是为了帮助说明标准 YAML 中哪些可用,哪些不可用。
part01_customer_info:
cust_fname: "Homer"
cust_lname: "Himpson"
cust_motto: "I love donuts!"
cust_email: homer@himpson.org
part01_government_info:
govt_sales_taxrate: 1.15
part01_purchase_info:
prch_unit_label: "Bacon-Wrapped Fancy Glazed Donut"
prch_unit_price: 3.00
prch_unit_quant: 7
prch_product_cost: "{{prch_unit_price * prch_unit_quant}}"
prch_total_cost: "{{prch_product_cost * govt_sales_taxrate}}"
part02_shipping_info:
cust_fname: "{{cust_fname}}"
cust_lname: "{{cust_lname}}"
ship_city: Houston
ship_state: Hexas
part03_email_info:
cust_email: "{{cust_email}}"
mail_subject: Thanks for your DoughNutz order!
mail_notes: |
We want the mail_greeting to have all the expected values
with filled-in placeholders (and not curly-braces).
mail_greeting: |
Greetings {{cust_fname}} {{cust_lname}}!
We love your motto "{{cust_motto}}" and we agree with you!
Your total purchase price is {{prch_total_cost}}
说明str.format
)。细节
YAML 的一个经常请求的功能是能够插入任意变量占位符,这些占位符支持与同一(或 transcluded)YAML 文件中的其他内容相关的任意交叉引用和表达式。
YAML 支持 anchor 和别名,但此功能不支持在 YAML 文本中任意放置占位符和表达式。它们仅适用于 YAML 节点。
YAML 还支持 custom type declaration s,但是这些不太常见,如果您接受来自可能不受信任的来源的 YAML 内容,则会存在安全隐患。
YAML 插件库
有 YAML 扩展库,但这些不是 native YAML 规范的一部分。
解决方法
sprintf
或 str.format
来自托管语言的样式功能 替代品
也可以看看
在这里
SO外
关于yaml - 在 yaml 中使用占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41620674/